ttui 2.0.0

A terminal UI framework built from first principles: direct control over text rendering, color, pane layout, and multiplexing.
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
//! Raw-mode terminal setup/teardown: entering the alternate screen,
//! diff-based redraws, input polling, and panic-safe cleanup.

use std::io::{stdout, BufWriter, Stdout, Write};
use std::time::Duration;

use crossterm::event::{self, Event};
use crossterm::style::{
    Attribute, Color, Print, SetAttribute, SetBackgroundColor, SetForegroundColor,
};
use crossterm::{cursor, execute, queue, terminal};

use crate::buffer::{CellDiff, Intensity};

/// A raw-mode, alternate-screen terminal handle. Restores normal
/// terminal state automatically on drop.
pub struct Terminal {
    out: BufWriter<Stdout>,
}

impl Terminal {
    /// Enables raw mode, enters the alternate screen, hides the cursor,
    /// and enables mouse capture.
    pub fn new() -> std::io::Result<Self> {
        terminal::enable_raw_mode()?;
        let mut out = BufWriter::new(stdout());
        execute!(
            out,
            terminal::EnterAlternateScreen,
            cursor::Hide,
            event::EnableMouseCapture
        )?;
        Ok(Terminal { out })
    }

    /// Current terminal size in cells, `(width, height)`.
    pub fn size(&self) -> std::io::Result<(u16, u16)> {
        terminal::size()
    }

    /// Writes only the given changed cells to the terminal, then
    /// flushes once. Thin wrapper over [`render_diff`].
    pub fn draw_diff(&mut self, diffs: &[CellDiff]) -> std::io::Result<()> {
        render_diff(&mut self.out, diffs)?;
        self.out.flush()
    }

    /// Polls for one input event, up to `timeout`; `None` on timeout.
    /// Motion-only mouse events (`Moved`/`Drag`) are discarded rather
    /// than returned — see `is_ignorable_mouse_motion` for why.
    pub fn next_event(&self, timeout: Duration) -> std::io::Result<Option<Event>> {
        let deadline = std::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                return Ok(None);
            }
            if !event::poll(remaining)? {
                return Ok(None);
            }
            let event = event::read()?;
            if !is_ignorable_mouse_motion(&event) {
                return Ok(Some(event));
            }
        }
    }
}

/// Whether `next_event` should silently discard this event instead of
/// returning it. `?1003h` "any-motion" mouse tracking (enabled as part of
/// `EnableMouseCapture`) reports every mouse movement over the terminal,
/// far faster than any example's poll timeout — left undiscarded, this
/// would starve `App::on_tick` (only fires on a real timeout) and force a
/// redraw on every pixel of movement, in every example, not just ones
/// that use the mouse.
fn is_ignorable_mouse_motion(event: &Event) -> bool {
    matches!(
        event,
        Event::Mouse(m) if matches!(m.kind, event::MouseEventKind::Moved | event::MouseEventKind::Drag(_))
    )
}

/// Encodes `diffs` as terminal control sequences into `writer`,
/// coalescing redundant cursor moves and SGR changes; does not flush.
/// The lower-level primitive [`Terminal::draw_diff`] wraps with a
/// buffered stdout and a single flush.
pub fn render_diff(writer: &mut impl Write, diffs: &[CellDiff]) -> std::io::Result<()> {
    let mut last_pos: Option<(u16, u16)> = None;
    let mut last_fg: Option<Color> = None;
    let mut last_bg: Option<Color> = None;
    let mut last_intensity: Option<Intensity> = None;
    let mut last_underline: Option<bool> = None;
    let mut last_italic: Option<bool> = None;
    let mut last_reverse: Option<bool> = None;
    let mut last_strikethrough: Option<bool> = None;

    for d in diffs {
        // Move only when this cell isn't the previous cell's right
        // neighbor — after Print the cursor already sits there. A run
        // can't cross a row end, so autowrap is never relied upon.
        let contiguous =
            matches!(last_pos, Some((px, py)) if py == d.y && d.x.checked_sub(1) == Some(px));
        if !contiguous {
            queue!(writer, cursor::MoveTo(d.x, d.y))?;
        }

        // NormalIntensity (not a full SGR reset) clears bold/dim without
        // touching color, so fg/bg can be tracked independently.
        let intensity = d.cell.style.intensity;
        if last_intensity != Some(intensity) {
            let attr = match intensity {
                Intensity::Normal => Attribute::NormalIntensity,
                Intensity::Bold => Attribute::Bold,
                Intensity::Dim => Attribute::Dim,
            };
            queue!(writer, SetAttribute(attr))?;
            last_intensity = Some(intensity);
        }
        let underline = d.cell.style.underline;
        if last_underline != Some(underline) {
            let attr = if underline {
                Attribute::Underlined
            } else {
                Attribute::NoUnderline
            };
            queue!(writer, SetAttribute(attr))?;
            last_underline = Some(underline);
        }
        let italic = d.cell.style.italic;
        if last_italic != Some(italic) {
            let attr = if italic {
                Attribute::Italic
            } else {
                Attribute::NoItalic
            };
            queue!(writer, SetAttribute(attr))?;
            last_italic = Some(italic);
        }
        let reverse = d.cell.style.reverse;
        if last_reverse != Some(reverse) {
            let attr = if reverse {
                Attribute::Reverse
            } else {
                Attribute::NoReverse
            };
            queue!(writer, SetAttribute(attr))?;
            last_reverse = Some(reverse);
        }
        let strikethrough = d.cell.style.strikethrough;
        if last_strikethrough != Some(strikethrough) {
            let attr = if strikethrough {
                Attribute::CrossedOut
            } else {
                Attribute::NotCrossedOut
            };
            queue!(writer, SetAttribute(attr))?;
            last_strikethrough = Some(strikethrough);
        }
        if last_fg != Some(d.cell.fg) {
            queue!(writer, SetForegroundColor(d.cell.fg))?;
            last_fg = Some(d.cell.fg);
        }
        if last_bg != Some(d.cell.bg) {
            queue!(writer, SetBackgroundColor(d.cell.bg))?;
            last_bg = Some(d.cell.bg);
        }
        queue!(writer, Print(d.cell.symbol))?;
        last_pos = Some((d.x, d.y));
    }
    Ok(())
}

impl Drop for Terminal {
    fn drop(&mut self) {
        let _ = execute!(self.out, SetAttribute(Attribute::Reset));
        // DisableMouseCapture must run before disable_raw_mode(): on
        // Windows, crossterm's mouse-capture toggle caches the console
        // mode at EnableMouseCapture time and restores exactly that
        // snapshot on DisableMouseCapture. Since EnableMouseCapture runs
        // after enable_raw_mode() in `new()`, that cached snapshot still
        // has raw mode on — running DisableMouseCapture after
        // disable_raw_mode() would silently re-enable raw mode by
        // restoring over it.
        let _ = execute!(self.out, event::DisableMouseCapture);
        let _ = terminal::disable_raw_mode();
        let _ = execute!(self.out, terminal::LeaveAlternateScreen, cursor::Show);
    }
}

/// Wraps the default panic hook so a panic mid-raw-mode still restores
/// normal terminal state before printing the panic message.
pub fn install_panic_hook() {
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = execute!(stdout(), SetAttribute(Attribute::Reset));
        // See the matching comment in `Drop for Terminal` — order matters.
        let _ = execute!(stdout(), event::DisableMouseCapture);
        let _ = terminal::disable_raw_mode();
        let _ = execute!(stdout(), terminal::LeaveAlternateScreen, cursor::Show);
        default_hook(info);
    }));
}

#[cfg(test)]
mod render_diff_tests {
    use super::*;
    use crate::buffer::{Cell, CellDiff, CellStyle, Intensity};
    use crossterm::style::Color;

    fn d(x: u16, y: u16, symbol: char, fg: Color, bg: Color, intensity: Intensity) -> CellDiff {
        CellDiff {
            x,
            y,
            cell: Cell {
                symbol,
                fg,
                bg,
                style: CellStyle {
                    intensity,
                    ..Default::default()
                },
                alpha: 1.0,
            },
        }
    }

    fn styled(x: u16, y: u16, symbol: char, style: CellStyle) -> CellDiff {
        CellDiff {
            x,
            y,
            cell: Cell {
                symbol,
                fg: Color::Reset,
                bg: Color::Reset,
                style,
                alpha: 1.0,
            },
        }
    }

    fn render(diffs: &[CellDiff]) -> Vec<u8> {
        let mut buf = Vec::new();
        render_diff(&mut buf, diffs).unwrap();
        buf
    }

    /// Bytes crossterm emits for a single command — lets assertions
    /// count real control sequences without hard-coding ANSI codes.
    fn encode<C: crossterm::Command>(cmd: C) -> Vec<u8> {
        let mut v = Vec::new();
        crossterm::queue!(&mut v, cmd).unwrap();
        v
    }

    fn count(hay: &[u8], needle: &[u8]) -> usize {
        if needle.is_empty() || needle.len() > hay.len() {
            return 0;
        }
        hay.windows(needle.len()).filter(|w| *w == needle).count()
    }

    // Number of MoveTo commands == number of CSI cursor-position
    // terminators ('H'); test glyphs are never 'H'.
    fn move_count(out: &[u8]) -> usize {
        count(out, b"H")
    }

    #[test]
    fn empty_diffs_produce_no_output() {
        assert!(render(&[]).is_empty());
    }

    #[test]
    fn single_diff_emits_move_colors_intensity_and_glyph() {
        let out = render(&[d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal)]);
        assert_eq!(move_count(&out), 1);
        assert!(out.contains(&b'A'));
        assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
        assert_eq!(count(&out, &encode(SetBackgroundColor(Color::Reset))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
            1
        );
    }

    #[test]
    fn contiguous_same_styled_run_moves_once_and_sets_style_once() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(move_count(&out), 1, "contiguous run needs one MoveTo");
        assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
        assert_eq!(count(&out, &encode(SetBackgroundColor(Color::Reset))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
            1
        );
        assert!(out.contains(&b'A') && out.contains(&b'B'));
    }

    #[test]
    fn positional_gap_forces_a_second_move() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(6, 2, 'B', Color::Reset, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(move_count(&out), 2);
    }

    #[test]
    fn new_row_forces_a_second_move() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(4, 3, 'B', Color::Reset, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(move_count(&out), 2);
    }

    #[test]
    fn color_change_mid_run_re_emits_that_color_only() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(4, 2, 'B', Color::Red, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(move_count(&out), 1, "still contiguous");
        assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
        assert_eq!(count(&out, &encode(SetForegroundColor(Color::Red))), 1);
        assert_eq!(
            count(&out, &encode(SetBackgroundColor(Color::Reset))),
            1,
            "bg unchanged, emitted once"
        );
    }

    #[test]
    fn bold_toggle_emits_intensity_transitions() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Bold),
            d(5, 2, 'C', Color::Reset, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
            2,
            "first cell + bold-off transition"
        );
    }

    #[test]
    fn intensity_cycles_through_all_three_states() {
        let out = render(&[
            d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
            d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Bold),
            d(5, 2, 'C', Color::Reset, Color::Reset, Intensity::Dim),
            d(6, 2, 'D', Color::Reset, Color::Reset, Intensity::Normal),
        ]);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
            2,
            "first cell (Normal) + final Normal transition"
        );
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Dim))), 1);
    }

    #[test]
    fn underline_toggle_emits_underlined_and_no_underline() {
        let out = render(&[
            styled(3, 2, 'A', CellStyle::default()),
            styled(
                4,
                2,
                'B',
                CellStyle {
                    underline: true,
                    ..Default::default()
                },
            ),
            styled(5, 2, 'C', CellStyle::default()),
        ]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Underlined))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NoUnderline))),
            2,
            "first cell + underline-off transition"
        );
    }

    #[test]
    fn italic_toggle_emits_italic_and_no_italic() {
        let out = render(&[
            styled(3, 2, 'A', CellStyle::default()),
            styled(
                4,
                2,
                'B',
                CellStyle {
                    italic: true,
                    ..Default::default()
                },
            ),
            styled(5, 2, 'C', CellStyle::default()),
        ]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Italic))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NoItalic))),
            2,
            "first cell + italic-off transition"
        );
    }

    #[test]
    fn reverse_toggle_emits_reverse_and_no_reverse() {
        let out = render(&[
            styled(3, 2, 'A', CellStyle::default()),
            styled(
                4,
                2,
                'B',
                CellStyle {
                    reverse: true,
                    ..Default::default()
                },
            ),
            styled(5, 2, 'C', CellStyle::default()),
        ]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Reverse))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NoReverse))),
            2,
            "first cell + reverse-off transition"
        );
    }

    #[test]
    fn strikethrough_toggle_emits_crossed_out_and_not_crossed_out() {
        let out = render(&[
            styled(3, 2, 'A', CellStyle::default()),
            styled(
                4,
                2,
                'B',
                CellStyle {
                    strikethrough: true,
                    ..Default::default()
                },
            ),
            styled(5, 2, 'C', CellStyle::default()),
        ]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::CrossedOut))), 1);
        assert_eq!(
            count(&out, &encode(SetAttribute(Attribute::NotCrossedOut))),
            2,
            "first cell + strikethrough-off transition"
        );
    }

    #[test]
    fn all_five_style_axes_combine_independently_in_one_cell() {
        let out = render(&[styled(
            3,
            2,
            'A',
            CellStyle {
                intensity: Intensity::Bold,
                underline: true,
                italic: true,
                reverse: true,
                strikethrough: true,
            },
        )]);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Underlined))), 1);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Italic))), 1);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::Reverse))), 1);
        assert_eq!(count(&out, &encode(SetAttribute(Attribute::CrossedOut))), 1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
    use crossterm::terminal;

    fn mouse_event(kind: MouseEventKind) -> Event {
        Event::Mouse(MouseEvent {
            kind,
            column: 0,
            row: 0,
            modifiers: crossterm::event::KeyModifiers::NONE,
        })
    }

    #[test]
    fn moved_mouse_events_are_ignorable() {
        assert!(is_ignorable_mouse_motion(&mouse_event(
            MouseEventKind::Moved
        )));
    }

    #[test]
    fn drag_mouse_events_are_ignorable() {
        assert!(is_ignorable_mouse_motion(&mouse_event(
            MouseEventKind::Drag(MouseButton::Left)
        )));
    }

    #[test]
    fn click_mouse_events_are_not_ignorable() {
        assert!(!is_ignorable_mouse_motion(&mouse_event(
            MouseEventKind::Down(MouseButton::Left)
        )));
    }

    #[test]
    fn key_events_are_not_ignorable() {
        assert!(!is_ignorable_mouse_motion(&Event::Key(KeyEvent::from(
            KeyCode::Char('a')
        ))));
    }

    #[test]
    #[ignore = "requires a real terminal (TTY); run with `cargo test -- --ignored`"]
    fn enter_and_drop_restores_raw_mode() {
        assert!(!terminal::is_raw_mode_enabled().unwrap());
        {
            let _term = Terminal::new().unwrap();
            assert!(terminal::is_raw_mode_enabled().unwrap());
        }
        assert!(!terminal::is_raw_mode_enabled().unwrap());
    }

    #[test]
    #[ignore = "requires a real terminal (TTY); run with `cargo test -- --ignored`"]
    fn panic_hook_disables_raw_mode_before_unwinding() {
        install_panic_hook();
        terminal::enable_raw_mode().unwrap();
        assert!(terminal::is_raw_mode_enabled().unwrap());

        let result = std::panic::catch_unwind(|| {
            panic!("simulated crash");
        });

        assert!(result.is_err());
        assert!(!terminal::is_raw_mode_enabled().unwrap());
    }
}