oxi-tui 0.5.0

Terminal UI framework with differential rendering, themes, and components
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! TUI - Main Terminal UI framework.
//!
//! This module provides the core TUI struct and event loop for building
//! terminal-based user interfaces with differential rendering.

use crate::{
    cell::Cell,
    component::Component,
    event::{
        KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, ResizeEvent,
    },
    layout::{split, Constraint, Direction},
    overlay::{OverlayBox, OverlayContent, OverlayHandle, OverlayOptions},
    renderer::Renderer,
    surface::Surface,
    terminal::{CrosstermTerminal, Size, Terminal},
};
use anyhow::Result;
use std::io::{self, stdout, Write};

/// Rendering strategy based on change type.
enum RenderStrategy {
    /// Full redraw needed (first render, width change, or large changes).
    Full,
    /// Incremental update (only dirty lines).
    Incremental,
}

/// Main TUI struct - the entry point for building terminal UIs.
pub struct TUI {
    /// The terminal backend.
    terminal: Box<dyn Terminal>,
    /// Child components in z-order (0 = bottom).
    children: Vec<Box<dyn Component>>,
    /// Currently focused component index.
    focus_index: usize,
    /// Overlay stack.
    overlay_stack: Vec<OverlayHandleWrapper>,
    /// Whether a render is needed.
    dirty: bool,
    /// Previous surface for diff comparison.
    prev_surface: Option<Surface>,
    /// Renderer instance.
    renderer: Renderer,
    /// Surface size tracking.
    last_width: u16,
    last_height: u16,
    /// Running state.
    running: bool,
    /// Whether we have a pending cursor position query (ESC[6n sent).
    cursor_marker_pending: bool,
    /// Event handle callback.
    event_handler: Option<Box<dyn FnMut(crate::Event) + Send>>,
    /// Layout for arranging children.
    layout: Option<(Direction, Vec<Constraint>)>,
}

struct OverlayHandleWrapper {
    overlay: Box<dyn OverlayHandle>,
}

impl TUI {
    /// Create a new TUI instance with a default terminal.
    pub fn new(mut terminal: impl Terminal + 'static) -> Self {
        let size = terminal.size().unwrap_or(Size {
            width: 80,
            height: 24,
        });
        Self {
            terminal: Box::new(terminal),
            children: Vec::new(),
            focus_index: 0,
            overlay_stack: Vec::new(),
            dirty: true,
            prev_surface: None,
            renderer: Renderer::new(),
            last_width: size.width,
            last_height: size.height,
            running: false,
            cursor_marker_pending: false,
            event_handler: None,
            layout: None,
        }
    }

    /// Create with crossterm backend (convenience constructor).
    pub fn with_crossterm() -> Result<Self> {
        let terminal = CrosstermTerminal::new()?;
        Ok(Self::new(terminal))
    }

    /// Add a child component.
    pub fn add_child(&mut self, component: impl Component + 'static) -> usize {
        let index = self.children.len();
        self.children.push(Box::new(component));
        self.request_render();
        index
    }

    /// Remove a child component by index.
    pub fn remove_child(&mut self, index: usize) {
        if index < self.children.len() {
            self.children.remove(index);
            if self.focus_index >= self.children.len() && !self.children.is_empty() {
                self.focus_index = self.children.len() - 1;
            }
            self.request_render();
        }
    }

    /// Set focus to a component by index.
    pub fn set_focus(&mut self, index: usize) {
        if index < self.children.len() {
            // Unfocus previous
            if self.focus_index < self.children.len() {
                if let Some(child) = self.children.get_mut(self.focus_index) {
                    child.unfocus();
                }
            }
            self.focus_index = index;
            // Focus new
            if let Some(child) = self.children.get_mut(index) {
                child.focus();
            }
            self.request_render();
        }
    }

    /// Get current focus index.
    pub fn focus_index(&self) -> usize {
        self.focus_index
    }

    /// Get number of children.
    pub fn children_count(&self) -> usize {
        self.children.len()
    }

    /// Add an overlay.
    pub fn add_overlay<T: OverlayContent + 'static>(
        &mut self,
        content: T,
        options: OverlayOptions,
    ) -> usize {
        let id = self.overlay_stack.len();
        let mut boxed = OverlayBox::new(content, options);
        boxed.set_id(id);

        self.overlay_stack.push(OverlayHandleWrapper {
            overlay: Box::new(boxed),
        });
        self.request_render();
        id
    }

    /// Remove an overlay by index.
    pub fn remove_overlay(&mut self, id: usize) {
        if id < self.overlay_stack.len() {
            self.overlay_stack.remove(id);
            self.request_render();
        }
    }

    /// Remove all overlays.
    pub fn clear_overlays(&mut self) {
        self.overlay_stack.clear();
        self.request_render();
    }

    /// Mark the TUI as needing a render.
    pub fn request_render(&mut self) {
        self.dirty = true;
    }

    /// Set an event handler callback.
    pub fn on_event(&mut self, handler: impl FnMut(crate::Event) + Send + 'static) {
        self.event_handler = Some(Box::new(handler));
    }

    /// Set a layout for arranging children.
    pub fn set_layout(&mut self, direction: Direction, constraints: Vec<Constraint>) {
        self.layout = Some((direction, constraints));
        self.request_render();
    }

    /// Clear the layout (children will be rendered full-area).
    pub fn clear_layout(&mut self) {
        self.layout = None;
        self.request_render();
    }

    /// Start the TUI event loop.
    ///
    /// This enters alternate screen mode and runs until `stop()` is called.
    pub fn start(&mut self) -> Result<()> {
        if self.running {
            return Ok(());
        }
        self.running = true;

        // Enter alternate screen
        crossterm::execute!(stdout(), crossterm::terminal::EnterAlternateScreen)?;
        crossterm::execute!(stdout(), crossterm::cursor::Hide)?;

        // Enable mouse reporting
        crossterm::execute!(stdout(), crossterm::event::EnableMouseCapture)?;

        // Initial render
        self.render()?;

        // Main event loop
        while self.running {
            // Poll for events with a timeout
            if let Some(event) = self.poll_event(std::time::Duration::from_millis(16)) {
                self.handle_event(event);
            }

            // Render if dirty
            if self.dirty {
                self.render()?;
            }
        }

        // Cleanup
        self.cleanup()?;

        Ok(())
    }

    /// Stop the TUI event loop.
    pub fn stop(&mut self) {
        self.running = false;
    }

    /// Check if TUI is running.
    pub fn is_running(&self) -> bool {
        self.running
    }

    /// Request a cursor position report from the terminal.
    ///
    /// Sends `ESC[6n` to the terminal. When the terminal responds with
    /// `ESC[row;colR`, the next call to [`poll_event`](Self::poll_event)
    /// will return [`Event::CursorPosition(row, col)`](crate::Event::CursorPosition).
    ///
    /// This is useful for IME (Input Method Editor) support: after rendering,
    /// call this to discover where the cursor is, so the hardware cursor can
    /// be placed at the text input position for CJK input methods.
    pub fn request_cursor_position_query(&mut self) -> Result<()> {
        self.cursor_marker_pending = true;
        self.terminal.query_cursor_position()?;
        Ok(())
    }

    /// Set the IME cursor position for the next render.
    ///
    /// The cursor will be placed at `(row, col)` after the frame is flushed,
    /// and the cursor will be made visible. This is needed for terminals to
    /// show the IME composition window at the correct position.
    pub fn set_ime_cursor(&mut self, row: u16, col: u16) {
        self.renderer.set_cursor_position(Some((row, col)));
    }

    /// Clear the IME cursor positioning.
    pub fn clear_ime_cursor(&mut self) {
        self.renderer.set_cursor_position(None);
    }

    /// Poll for a single event (non-blocking with timeout).
    ///
    /// When a cursor position query is pending (`cursor_marker_pending = true`),
    /// this method attempts to parse the terminal's CSI response from crossterm's
    /// event stream. Crossterm internally consumes `ESC[row;colR` as an
    /// `InternalEvent::CursorPosition`, but its public `Event` enum does not
    /// expose it. As a fallback, we check the cursor position synchronously
    /// via the terminal's `cursor_pos()` method.
    fn poll_event(&mut self, timeout: std::time::Duration) -> Option<crate::Event> {
        // If we have a pending cursor position query, try to get the response.
        // We attempt a non-blocking poll first; if crossterm reports an event
        // is available, we read it normally. If not, and we're still pending,
        // we do a synchronous cursor position query.
        if self.cursor_marker_pending {
            // Give the terminal a brief window to respond
            if !crossterm::event::poll(std::time::Duration::from_millis(5)).ok()? {
                // No regular event — try to read the cursor position synchronously.
                // This sends ESC[6n and blocks for the response internally.
                self.cursor_marker_pending = false;
                if let Ok(pos) = self.terminal.cursor_pos() {
                    return Some(crate::Event::CursorPosition(pos.row, pos.col));
                }
                return None;
            }
            // Event is available — read it via crossterm (cursor position report
            // will be consumed internally and discarded by the EventFilter).
            // Fall through to normal handling.
            self.cursor_marker_pending = false;
        }

        if crossterm::event::poll(timeout).ok()? {
            crossterm::event::read().ok().map(Self::convert_event)
        } else {
            None
        }
    }

    /// Convert crossterm events to our Event type.
    fn convert_event(event: crossterm::event::Event) -> crate::Event {
        match event {
            crossterm::event::Event::Key(key) => {
                let code = match key.code {
                    crossterm::event::KeyCode::Enter => KeyCode::Enter,
                    crossterm::event::KeyCode::Esc => KeyCode::Escape,
                    crossterm::event::KeyCode::Tab => KeyCode::Tab,
                    crossterm::event::KeyCode::Backspace => KeyCode::Backspace,
                    crossterm::event::KeyCode::Delete => KeyCode::Delete,
                    crossterm::event::KeyCode::Up => KeyCode::Up,
                    crossterm::event::KeyCode::Down => KeyCode::Down,
                    crossterm::event::KeyCode::Left => KeyCode::Left,
                    crossterm::event::KeyCode::Right => KeyCode::Right,
                    crossterm::event::KeyCode::Home => KeyCode::Home,
                    crossterm::event::KeyCode::End => KeyCode::End,
                    crossterm::event::KeyCode::PageUp => KeyCode::PageUp,
                    crossterm::event::KeyCode::PageDown => KeyCode::PageDown,
                    crossterm::event::KeyCode::Insert => KeyCode::Insert,
                    crossterm::event::KeyCode::F(n) => KeyCode::F(n),
                    crossterm::event::KeyCode::Char(c) => KeyCode::Char(c),
                    _ => KeyCode::Enter, // Handle unknown keys
                };

                let modifiers = KeyModifiers {
                    shift: key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::SHIFT),
                    ctrl: key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL),
                    alt: key.modifiers.contains(crossterm::event::KeyModifiers::ALT),
                    meta: key.modifiers.contains(crossterm::event::KeyModifiers::META),
                };

                crate::Event::Key(KeyEvent::with_modifiers(code, modifiers))
            }
            crossterm::event::Event::Mouse(mouse) => {
                let kind = match mouse.kind {
                    crossterm::event::MouseEventKind::Down(_btn) => MouseEventKind::Press,
                    crossterm::event::MouseEventKind::Up(_btn) => MouseEventKind::Release,
                    crossterm::event::MouseEventKind::Drag(_btn) => MouseEventKind::Drag,
                    crossterm::event::MouseEventKind::Moved => MouseEventKind::Moved,
                    crossterm::event::MouseEventKind::ScrollDown => MouseEventKind::ScrollDown,
                    crossterm::event::MouseEventKind::ScrollUp => MouseEventKind::ScrollUp,
                    crossterm::event::MouseEventKind::ScrollLeft => MouseEventKind::ScrollLeft,
                    crossterm::event::MouseEventKind::ScrollRight => MouseEventKind::ScrollRight,
                };

                let button = match mouse.kind {
                    crossterm::event::MouseEventKind::Down(btn)
                    | crossterm::event::MouseEventKind::Up(btn)
                    | crossterm::event::MouseEventKind::Drag(btn) => match btn {
                        crossterm::event::MouseButton::Left => MouseButton::Left,
                        crossterm::event::MouseButton::Right => MouseButton::Right,
                        crossterm::event::MouseButton::Middle => MouseButton::Middle,
                    },
                    _ => MouseButton::None,
                };

                crate::Event::Mouse(MouseEvent {
                    kind,
                    button,
                    row: mouse.row,
                    col: mouse.column,
                })
            }
            crossterm::event::Event::Resize(cols, rows) => crate::Event::Resize(ResizeEvent {
                width: cols,
                height: rows,
            }),
            crossterm::event::Event::FocusGained => crate::Event::FocusGained,
            crossterm::event::Event::FocusLost => crate::Event::FocusLost,
            _ => crate::Event::None,
        }
    }

    /// Handle an input event.
    fn handle_event(&mut self, event: crate::Event) {
        // Handle overlay events first (for modals)
        if let Some(top) = self.overlay_stack.last_mut() {
            if top.overlay.is_hidden() {
                return;
            }
            // Try overlay first
            if top.overlay.handle_event(&event) {
                self.request_render();
                return;
            }
        }

        // Check Escape for closing overlays
        if let crate::Event::Key(ref key) = event {
            if key.code == KeyCode::Escape && !self.overlay_stack.is_empty() {
                self.overlay_stack.pop();
                self.request_render();
                return;
            }
        }

        // Pass to focused component
        if self.focus_index < self.children.len()
            && self.children[self.focus_index].handle_event(&event) {
                self.request_render();
                return;
            }

        // Global key handling
        if let crate::Event::Key(key) = &event {
            match key.code {
                // Tab cycles focus
                KeyCode::Tab => {
                    if self.children.len() > 1 {
                        let next = if key.modifiers.shift {
                            self.focus_index.saturating_sub(1)
                        } else {
                            (self.focus_index + 1) % self.children.len()
                        };
                        self.set_focus(next);
                    }
                }
                // Ctrl+C exits
                KeyCode::Char('c') if key.modifiers.ctrl => {
                    self.stop();
                }
                _ => {}
            }
        }

        // Call event handler if set
        if let Some(ref mut handler) = self.event_handler {
            handler(event);
        }
    }

    /// Render the current state.
    fn render(&mut self) -> Result<()> {
        let size = self.terminal.size()?;

        // Determine render strategy
        let strategy = self.determine_render_strategy(size);

        // Create surface for this frame
        let mut surface = Surface::new(size.width, size.height);

        // Clear to spaces
        let empty_cell = Cell::new(' ');
        surface.fill(empty_cell);

        // Render children
        let area = surface.area();
        if let Some((ref direction, ref constraints)) = self.layout {
            let areas = split(area, *direction, constraints);
            for (i, child) in self.children.iter_mut().enumerate() {
                if let Some(&child_area) = areas.get(i) {
                    child.render(&mut surface, child_area);
                }
            }
        } else {
            for child in &mut self.children {
                child.render(&mut surface, area);
            }
        }

        // Render overlays (on top)
        for overlay in &mut self.overlay_stack {
            if !overlay.overlay.is_hidden() {
                overlay.overlay.render(&mut surface, area);
            }
        }

        // Execute render based on strategy
        match strategy {
            RenderStrategy::Full => {
                self.renderer.begin_sync();
                self.renderer.clear_screen();
                for row in 0..size.height {
                    for col in 0..size.width {
                        if let Some(cell) = surface.get(row, col) {
                            self.renderer.render_cell(row, col, cell);
                        }
                    }
                }
                self.renderer.end_sync()?;
            }
            RenderStrategy::Incremental => {
                self.renderer.begin_sync();
                if let (Some(first), Some(last)) = (surface.first_dirty(), surface.last_dirty()) {
                    self.renderer.render_changed_lines(
                        &surface,
                        first,
                        last.min(size.height - 1),
                    )?;
                }
                self.renderer.end_sync()?;
            }
        }

        // Clear dirty state
        self.dirty = false;
        surface.clear_dirty();

        // Store for next diff
        self.prev_surface = Some(surface);

        // Hide cursor at end
        print!("\x1b[?25l");
        io::stdout().flush()?;

        Ok(())
    }

    /// Determine which rendering strategy to use.
    fn determine_render_strategy(&mut self, size: Size) -> RenderStrategy {
        // First render - full
        if self.prev_surface.is_none() {
            self.last_width = size.width;
            self.last_height = size.height;
            return RenderStrategy::Full;
        }

        // Width changed - full
        if size.width != self.last_width {
            self.last_width = size.width;
            self.last_height = size.height;
            return RenderStrategy::Full;
        }

        // Check if changes are above viewport (large scroll)
        // For now, always use incremental if there's a previous surface
        if let Some(ref prev) = self.prev_surface {
            if let (Some(_first), Some(last)) = (prev.first_dirty(), prev.last_dirty()) {
                // If change is in upper quarter of screen, full render
                if last > size.height / 4 * 3 {
                    return RenderStrategy::Full;
                }
            }
        }

        // Default to incremental
        RenderStrategy::Incremental
    }

    /// Cleanup on exit.
    fn cleanup(&mut self) -> Result<()> {
        // Show cursor
        crossterm::execute!(stdout(), crossterm::cursor::Show)?;

        // Disable mouse capture
        crossterm::execute!(stdout(), crossterm::event::DisableMouseCapture)?;

        // Leave alternate screen
        crossterm::execute!(stdout(), crossterm::terminal::LeaveAlternateScreen)?;

        // Flush output
        io::stdout().flush()?;

        Ok(())
    }

    /// Force a full redraw on next frame.
    pub fn force_redraw(&mut self) {
        if let Some(ref mut surf) = self.prev_surface {
            surf.mark_all_dirty();
        }
        self.dirty = true;
    }

    /// Get the current terminal size.
    pub fn size(&mut self) -> Result<Size> {
        self.terminal.size()
    }
}

impl Drop for TUI {
    fn drop(&mut self) {
        if self.running {
            // Ensure cleanup happens
            let _ = self.cleanup();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cell::Cell;
    use crate::terminal::{CursorVisibility, Position, Size, Terminal};

    /// A mock terminal that doesn't touch the real TTY.
    struct MockTerminal {
        size: Size,
    }

    impl MockTerminal {
        fn new(w: u16, h: u16) -> Self {
            Self {
                size: Size::new(w, h),
            }
        }
    }

    impl Terminal for MockTerminal {
        fn size(&mut self) -> anyhow::Result<Size> {
            Ok(self.size)
        }
        fn cursor_pos(&self) -> anyhow::Result<Position> {
            Ok(Position { row: 0, col: 0 })
        }
        fn set_cursor_pos(&mut self, _pos: Position) -> anyhow::Result<()> {
            Ok(())
        }
        fn set_cursor_visibility(&mut self, _v: CursorVisibility) -> anyhow::Result<()> {
            Ok(())
        }
        fn clear_screen(&mut self) -> anyhow::Result<()> {
            Ok(())
        }
        fn clear_line(&mut self) -> anyhow::Result<()> {
            Ok(())
        }
        fn flush(&mut self) -> anyhow::Result<()> {
            Ok(())
        }
        fn query_cursor_position(&mut self) -> anyhow::Result<()> {
            Ok(())
        }
        fn set_ime_cursor(&mut self, _row: u16, _col: u16) -> anyhow::Result<()> {
            Ok(())
        }
    }

    fn make_tui() -> TUI {
        TUI::new(MockTerminal::new(80, 24))
    }

    // --- TUI creation ---

    #[test]
    fn tui_creation() {
        let tui = make_tui();
        assert_eq!(tui.children_count(), 0);
        assert_eq!(tui.focus_index(), 0);
        assert!(!tui.is_running());
    }

    #[test]
    fn tui_default_size() {
        let mut tui = make_tui();
        let size = tui.size().unwrap();
        assert_eq!(size.width, 80);
        assert_eq!(size.height, 24);
    }

    #[test]
    fn tui_drop_does_not_panic() {
        // Creating and dropping should not panic even though start() was never called
        let tui = make_tui();
        drop(tui);
    }

    // --- Overlay stack management ---

    #[test]
    fn overlay_add_and_clear() {
        let mut tui = make_tui();

        // Create a simple overlay content
        struct TestOverlay;
        impl crate::component::Component for TestOverlay {
            fn request_render(&mut self) {}
            fn is_dirty(&self) -> bool { false }
            fn clear_dirty(&mut self) {}
            fn handle_event(&mut self, _event: &crate::Event) -> bool { false }
            fn render(&mut self, _surface: &mut Surface, _area: crate::Rect) {}
            fn min_size(&self) -> crate::terminal::Size { crate::terminal::Size::new(1, 1) }
        }
        impl crate::overlay::OverlayContent for TestOverlay {}

        let opts = crate::overlay::OverlayOptions::default();
        let id0 = tui.add_overlay(TestOverlay, opts.clone());
        assert_eq!(id0, 0);

        let id1 = tui.add_overlay(TestOverlay, opts);
        assert_eq!(id1, 1);

        // Remove overlay 0
        tui.remove_overlay(0);

        // Clear all
        tui.clear_overlays();
    }

    #[test]
    fn request_render_sets_dirty() {
        let mut tui = make_tui();
        tui.dirty = false;
        tui.request_render();
        assert!(tui.dirty);
    }

    // --- Render strategy heuristic ---

    #[test]
    fn render_strategy_first_render_is_full() {
        let mut tui = make_tui();
        // No prev_surface → Full
        let size = Size::new(80, 24);
        let strategy = tui.determine_render_strategy(size);
        assert!(matches!(strategy, RenderStrategy::Full));
    }

    #[test]
    fn render_strategy_width_change_is_full() {
        let mut tui = make_tui();
        // Simulate first render done
        let size = Size::new(80, 24);
        let _ = tui.determine_render_strategy(size);
        // Now set a prev_surface
        tui.prev_surface = Some(Surface::new(80, 24));
        tui.last_width = 80;
        tui.last_height = 24;

        // Width changed
        let new_size = Size::new(120, 24);
        let strategy = tui.determine_render_strategy(new_size);
        assert!(matches!(strategy, RenderStrategy::Full));
    }

    #[test]
    fn render_strategy_same_size_is_incremental() {
        let mut tui = make_tui();
        // Set prev_surface with same dimensions
        let prev = Surface::new(80, 24);
        // No dirty rows → no first/last dirty → should go to Incremental default
        tui.prev_surface = Some(prev);
        tui.last_width = 80;
        tui.last_height = 24;

        let size = Size::new(80, 24);
        let strategy = tui.determine_render_strategy(size);
        assert!(matches!(strategy, RenderStrategy::Incremental));
    }

    #[test]
    fn render_strategy_dirty_in_lower_quarter_is_incremental() {
        let mut tui = make_tui();
        let mut prev = Surface::new(80, 24);
        // Mark row 5 as dirty (well below 3/4 of 24 = 18)
        prev.set(5, 0, Cell::new('X'));
        tui.prev_surface = Some(prev);
        tui.last_width = 80;
        tui.last_height = 24;

        let size = Size::new(80, 24);
        let strategy = tui.determine_render_strategy(size);
        assert!(matches!(strategy, RenderStrategy::Incremental));
    }

    #[test]
    fn render_strategy_dirty_in_upper_quarter_is_full() {
        let mut tui = make_tui();
        let mut prev = Surface::new(80, 24);
        // Mark row 22 as dirty (above 3/4 of 24 = 18)
        prev.set(22, 0, Cell::new('X'));
        tui.prev_surface = Some(prev);
        tui.last_width = 80;
        tui.last_height = 24;

        let size = Size::new(80, 24);
        let strategy = tui.determine_render_strategy(size);
        assert!(matches!(strategy, RenderStrategy::Full));
    }

    #[test]
    fn force_redraw_marks_prev_surface_dirty() {
        let mut tui = make_tui();
        tui.prev_surface = Some(Surface::new(80, 24));
        tui.dirty = false;
        tui.force_redraw();
        assert!(tui.dirty);
        if let Some(ref s) = tui.prev_surface {
            assert!(s.is_any_dirty());
        }
    }
}