Skip to main content

ftui_core/
inline_mode.rs

1#![forbid(unsafe_code)]
2
3//! Inline Mode Spike: Validates correctness-first inline mode strategies.
4//!
5//! This module implements the Phase -1 spike (bd-10i.1.1) to validate inline mode
6//! strategies for FrankenTUI. Inline mode preserves terminal scrollback while
7//! rendering a stable UI region + streaming logs.
8//!
9//! # Strategies Implemented
10//!
11//! - **Strategy A (Scroll-Region)**: Uses DECSTBM to constrain scrolling to a region.
12//! - **Strategy B (Overlay-Redraw)**: Save cursor, clear UI, write logs, redraw UI, restore.
13//! - **Strategy C (Hybrid)**: Overlay-redraw baseline with scroll-region optimization where safe.
14//!
15//! # Key Invariants
16//!
17//! 1. Cursor is restored after each frame present.
18//! 2. Terminal modes are restored on normal exit AND panic.
19//! 3. No full-screen clears in inline mode (preserves scrollback).
20//! 4. One writer owns terminal output (enforced by ownership).
21
22use std::io::{self, Write};
23
24use unicode_segmentation::UnicodeSegmentation;
25
26use crate::terminal_capabilities::TerminalCapabilities;
27
28// ============================================================================
29// ANSI Escape Sequences
30// ============================================================================
31
32/// DEC cursor save (ESC 7) - more portable than CSI s.
33const CURSOR_SAVE: &[u8] = b"\x1b7";
34
35/// DEC cursor restore (ESC 8) - more portable than CSI u.
36const CURSOR_RESTORE: &[u8] = b"\x1b8";
37
38/// CSI sequence to move cursor to position (1-indexed).
39fn cursor_position(row: u16, col: u16) -> Vec<u8> {
40    format!("\x1b[{};{}H", row, col).into_bytes()
41}
42
43/// Set scroll region (DECSTBM): CSI top ; bottom r (1-indexed).
44fn set_scroll_region(top: u16, bottom: u16) -> Vec<u8> {
45    format!("\x1b[{};{}r", top, bottom).into_bytes()
46}
47
48/// Reset scroll region to full screen: CSI r.
49const RESET_SCROLL_REGION: &[u8] = b"\x1b[r";
50
51/// Erase line from cursor to end: CSI 0 K.
52#[allow(dead_code)] // Kept for future use in inline mode optimization
53const ERASE_TO_EOL: &[u8] = b"\x1b[0K";
54
55/// Erase entire line: CSI 2 K.
56const ERASE_LINE: &[u8] = b"\x1b[2K";
57
58/// Synchronized output begin (DEC 2026): CSI ? 2026 h.
59const SYNC_BEGIN: &[u8] = b"\x1b[?2026h";
60
61/// Synchronized output end (DEC 2026): CSI ? 2026 l.
62const SYNC_END: &[u8] = b"\x1b[?2026l";
63
64// ============================================================================
65// Inline Mode Strategy
66// ============================================================================
67
68/// Inline mode rendering strategy.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70pub enum InlineStrategy {
71    /// Use scroll regions (DECSTBM) to anchor UI while logs scroll.
72    /// More efficient but less portable (muxes may misbehave).
73    ScrollRegion,
74
75    /// Overlay redraw: no scroll region. The runtime's `TerminalWriter`
76    /// batches log lines, erases the UI rows, streams the lines with
77    /// ordinary line feeds so the whole screen scrolls them into
78    /// scrollback, then redraws the UI (bottom-anchored UI; a top-anchored
79    /// UI keeps only the newest line). Works on any terminal; costs one UI
80    /// redraw per batch.
81    OverlayRedraw,
82
83    /// Hybrid: the same DECSTBM scroll region as `ScrollRegion` but without
84    /// synchronized-output brackets, verified at startup by the DECSTBM
85    /// self-test (`caps_probe::probe_scroll_region`); a terminal that
86    /// ignores the region is switched to `OverlayRedraw` before the first
87    /// frame.
88    #[default]
89    Hybrid,
90}
91
92impl InlineStrategy {
93    /// Select the strategy from capabilities, in this order:
94    /// - inside a terminal multiplexer (tmux/screen/zellij/WezTerm mux):
95    ///   `OverlayRedraw` (muxes may not handle scroll regions correctly);
96    /// - scroll region and synchronized output: `ScrollRegion`;
97    /// - scroll region without synchronized output: `Hybrid`;
98    /// - otherwise `OverlayRedraw`.
99    ///
100    /// The runtime then runs the DECSTBM self-test for `ScrollRegion` and
101    /// `Hybrid` and falls back to `OverlayRedraw` when the terminal does not
102    /// honour the region (`TerminalWriter::set_scroll_region_verified`).
103    #[must_use]
104    pub fn select(caps: &TerminalCapabilities) -> Self {
105        if caps.in_any_mux() {
106            // Muxes may not handle scroll regions correctly
107            InlineStrategy::OverlayRedraw
108        } else if caps.use_scroll_region() && caps.use_sync_output() {
109            // Modern terminal with full support
110            InlineStrategy::ScrollRegion
111        } else if caps.use_scroll_region() {
112            // Scroll region available but no sync output - use hybrid
113            InlineStrategy::Hybrid
114        } else {
115            // Fallback to most portable option
116            InlineStrategy::OverlayRedraw
117        }
118    }
119}
120
121// ============================================================================
122// Inline Mode Session
123// ============================================================================
124
125/// Configuration for inline mode rendering.
126#[derive(Debug, Clone, Copy)]
127pub struct InlineConfig {
128    /// Height of the UI region (bottom N rows).
129    pub ui_height: u16,
130
131    /// Total terminal height.
132    pub term_height: u16,
133
134    /// Total terminal width.
135    pub term_width: u16,
136
137    /// Rendering strategy to use.
138    pub strategy: InlineStrategy,
139
140    /// Use synchronized output (DEC 2026) if available.
141    pub use_sync_output: bool,
142}
143
144impl InlineConfig {
145    /// Create config for a UI region of given height.
146    #[must_use]
147    pub fn new(ui_height: u16, term_height: u16, term_width: u16) -> Self {
148        Self {
149            ui_height,
150            term_height,
151            term_width,
152            strategy: InlineStrategy::default(),
153            use_sync_output: false,
154        }
155    }
156
157    /// Set the rendering strategy.
158    #[must_use]
159    pub const fn with_strategy(mut self, strategy: InlineStrategy) -> Self {
160        self.strategy = strategy;
161        self
162    }
163
164    /// Enable synchronized output.
165    #[must_use]
166    pub const fn with_sync_output(mut self, enabled: bool) -> Self {
167        self.use_sync_output = enabled;
168        self
169    }
170
171    /// Row where the UI region starts (1-indexed for ANSI).
172    ///
173    /// Returns at least 1 (valid ANSI row).
174    #[must_use]
175    pub const fn ui_top_row(&self) -> u16 {
176        let row = self
177            .term_height
178            .saturating_sub(self.ui_height)
179            .saturating_add(1);
180        // Ensure we return at least row 1 (valid ANSI row)
181        if row == 0 { 1 } else { row }
182    }
183
184    /// Row where the log region ends (1-indexed for ANSI).
185    ///
186    /// Returns 0 if there's no room for logs (UI takes full height).
187    /// Callers should check for 0 before using this value.
188    #[must_use]
189    pub const fn log_bottom_row(&self) -> u16 {
190        self.ui_top_row().saturating_sub(1)
191    }
192
193    /// Check if the configuration is valid for inline mode.
194    ///
195    /// Returns `true` if there's room for both logs and UI.
196    #[must_use]
197    pub const fn is_valid(&self) -> bool {
198        self.ui_height > 0 && self.ui_height < self.term_height && self.term_height > 1
199    }
200}
201
202// ============================================================================
203// Inline Mode Renderer
204// ============================================================================
205
206/// Inline mode renderer implementing the one-writer rule.
207///
208/// This struct owns terminal output and enforces that all writes go through it.
209/// Cleanup is guaranteed via `Drop`.
210pub struct InlineRenderer<W: Write> {
211    writer: W,
212    config: InlineConfig,
213    scroll_region_set: bool,
214    in_sync_block: bool,
215    cursor_saved: bool,
216}
217
218impl<W: Write> InlineRenderer<W> {
219    /// Create a new inline renderer.
220    ///
221    /// # Arguments
222    /// * `writer` - The terminal output (takes ownership to enforce one-writer rule).
223    /// * `config` - Inline mode configuration.
224    pub fn new(writer: W, config: InlineConfig) -> Self {
225        Self {
226            writer,
227            config,
228            scroll_region_set: false,
229            in_sync_block: false,
230            cursor_saved: false,
231        }
232    }
233
234    #[inline]
235    fn sync_output_enabled(&self) -> bool {
236        self.config.use_sync_output && TerminalCapabilities::with_overrides().use_sync_output()
237    }
238
239    /// Initialize inline mode on the terminal.
240    ///
241    /// For scroll-region strategy, this sets up DECSTBM.
242    /// For overlay/hybrid strategy, this just prepares state.
243    pub fn enter(&mut self) -> io::Result<()> {
244        match self.config.strategy {
245            InlineStrategy::ScrollRegion => {
246                // Set scroll region to log area (top of screen to just above UI)
247                let log_bottom = self.config.log_bottom_row();
248                if log_bottom > 0 {
249                    self.writer.write_all(&set_scroll_region(1, log_bottom))?;
250                    self.scroll_region_set = true;
251                }
252            }
253            InlineStrategy::OverlayRedraw | InlineStrategy::Hybrid => {
254                // No setup needed for overlay-based modes.
255                // Hybrid uses overlay as baseline; scroll-region would be an
256                // internal optimization applied per-operation, not upfront.
257            }
258        }
259        self.writer.flush()
260    }
261
262    /// Exit inline mode, restoring terminal state.
263    pub fn exit(&mut self) -> io::Result<()> {
264        self.cleanup_internal()
265    }
266
267    /// Write log output (goes to scrollback region).
268    ///
269    /// In scroll-region mode: writes to current cursor position in scroll region.
270    /// In overlay mode: saves cursor, writes, then restores cursor.
271    ///
272    /// Returns `Ok(())` even if there's no log region (logs are silently dropped
273    /// when UI takes the full terminal height).
274    pub fn write_log(&mut self, text: &str) -> io::Result<()> {
275        let log_row = self.config.log_bottom_row();
276
277        // If there's no room for logs, silently drop
278        if log_row == 0 {
279            return Ok(());
280        }
281
282        match self.config.strategy {
283            InlineStrategy::ScrollRegion => {
284                // Cursor should be in scroll region; just write
285                let safe_text = Self::sanitize_scroll_region_log_text(text);
286                if !safe_text.is_empty() {
287                    self.writer.write_all(safe_text.as_bytes())?;
288                }
289            }
290            InlineStrategy::OverlayRedraw | InlineStrategy::Hybrid => {
291                // Save cursor, move to log area, write, restore
292                self.writer.write_all(CURSOR_SAVE)?;
293                self.cursor_saved = true;
294
295                // Move to bottom of log region
296                self.writer.write_all(&cursor_position(log_row, 1))?;
297                self.writer.write_all(ERASE_LINE)?;
298
299                // Keep overlay logging single-line so wraps/newlines never scribble
300                // into the UI region below.
301                let safe_line =
302                    sanitize_overlay_log_line(text, usize::from(self.config.term_width));
303                if !safe_line.is_empty() {
304                    self.writer.write_all(safe_line.as_bytes())?;
305                }
306
307                // Restore cursor
308                self.writer.write_all(CURSOR_RESTORE)?;
309                self.cursor_saved = false;
310            }
311        }
312        self.writer.flush()
313    }
314
315    /// Present a UI frame.
316    ///
317    /// # Invariants
318    /// - Cursor position is saved before and restored after.
319    /// - UI region is redrawn without affecting scrollback.
320    /// - Synchronized output wraps the operation if enabled.
321    pub fn present_ui<F>(&mut self, render_fn: F) -> io::Result<()>
322    where
323        F: FnOnce(&mut W, &InlineConfig) -> io::Result<()>,
324    {
325        if !self.config.is_valid() {
326            return Err(io::Error::new(
327                io::ErrorKind::InvalidInput,
328                "invalid inline mode configuration",
329            ));
330        }
331
332        let sync_output_enabled = self.sync_output_enabled();
333
334        // Begin sync output to prevent flicker.
335        if sync_output_enabled && !self.in_sync_block {
336            // Mark active before write so cleanup conservatively emits SYNC_END
337            // even if begin write fails after partial bytes.
338            self.in_sync_block = true;
339            if let Err(err) = self.writer.write_all(SYNC_BEGIN) {
340                // Best-effort immediate close to avoid leaving terminal state
341                // in synchronized-output mode on begin-write failure.
342                let _ = self.writer.write_all(SYNC_END);
343                self.in_sync_block = false;
344                let _ = self.writer.flush();
345                return Err(err);
346            }
347        }
348
349        // Save cursor position
350        self.writer.write_all(CURSOR_SAVE)?;
351        self.cursor_saved = true;
352
353        let operation_result = (|| -> io::Result<()> {
354            // Move to UI region
355            let ui_row = self.config.ui_top_row();
356            self.writer.write_all(&cursor_position(ui_row, 1))?;
357
358            // Clear and render each UI line
359            for row in 0..self.config.ui_height {
360                self.writer
361                    .write_all(&cursor_position(ui_row.saturating_add(row), 1))?;
362                self.writer.write_all(ERASE_LINE)?;
363            }
364
365            // Move back to start of UI and let caller render
366            self.writer.write_all(&cursor_position(ui_row, 1))?;
367            render_fn(&mut self.writer, &self.config)?;
368            Ok(())
369        })();
370
371        // Always attempt to restore terminal state even if rendering failed.
372        let restore_result = self.writer.write_all(CURSOR_RESTORE);
373        if restore_result.is_ok() {
374            self.cursor_saved = false;
375        }
376
377        let sync_end_result = if sync_output_enabled && self.in_sync_block {
378            let res = self.writer.write_all(SYNC_END);
379            if res.is_ok() {
380                self.in_sync_block = false;
381            }
382            Some(res)
383        } else {
384            if !sync_output_enabled {
385                // Defensive stale-state cleanup: clear internal state without
386                // emitting DEC 2026 when policy disables synchronized output.
387                self.in_sync_block = false;
388            }
389            None
390        };
391
392        let flush_result = self.writer.flush();
393
394        // If cleanup fails, surface that first so callers can treat terminal
395        // state restoration issues as higher-severity than render errors.
396        let cleanup_error = restore_result
397            .err()
398            .or_else(|| sync_end_result.and_then(Result::err))
399            .or_else(|| flush_result.err());
400        if let Some(err) = cleanup_error {
401            return Err(err);
402        }
403        operation_result
404    }
405
406    fn sanitize_scroll_region_log_text(text: &str) -> String {
407        let bytes = text.as_bytes();
408        let mut out = String::with_capacity(text.len());
409        let mut i = 0;
410
411        while i < bytes.len() {
412            match bytes[i] {
413                // ESC - strip full sequence payload (CSI/OSC/DCS/APC/single-char escapes).
414                0x1B => {
415                    i = Self::skip_escape_sequence(bytes, i);
416                }
417                // Preserve LF and normalize CR to LF.
418                0x0A => {
419                    out.push('\n');
420                    i += 1;
421                }
422                0x0D => {
423                    out.push('\n');
424                    i += 1;
425                }
426                // Strip remaining C0 controls and DEL.
427                0x00..=0x1F | 0x7F => {
428                    i += 1;
429                }
430                // Printable ASCII.
431                0x20..=0x7E => {
432                    out.push(bytes[i] as char);
433                    i += 1;
434                }
435                // UTF-8: decode and drop C1 controls (U+0080..U+009F).
436                _ => {
437                    if let Some((ch, len)) = Self::decode_utf8_char(&bytes[i..]) {
438                        if !('\u{0080}'..='\u{009F}').contains(&ch) {
439                            out.push(ch);
440                        }
441                        i += len;
442                    } else {
443                        i += 1;
444                    }
445                }
446            }
447        }
448
449        out
450    }
451
452    fn skip_escape_sequence(bytes: &[u8], start: usize) -> usize {
453        let mut i = start + 1; // Skip ESC
454        if i >= bytes.len() {
455            return i;
456        }
457
458        match bytes[i] {
459            // CSI sequence: ESC [ params... final_byte
460            b'[' => {
461                i += 1;
462                while i < bytes.len() {
463                    let b = bytes[i];
464                    if (0x40..=0x7E).contains(&b) {
465                        return i + 1;
466                    }
467                    if !(0x20..=0x3F).contains(&b) {
468                        return i;
469                    }
470                    i += 1;
471                }
472            }
473            // OSC sequence: ESC ] ... (BEL or ST)
474            b']' => {
475                i += 1;
476                while i < bytes.len() {
477                    let b = bytes[i];
478                    if b == 0x07 {
479                        return i + 1;
480                    }
481                    if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
482                        return i + 2;
483                    }
484                    if b == 0x1B || b < 0x20 {
485                        return i;
486                    }
487                    i += 1;
488                }
489            }
490            // DCS/PM/APC: ESC P/^/_ ... ST
491            b'P' | b'^' | b'_' => {
492                i += 1;
493                while i < bytes.len() {
494                    let b = bytes[i];
495                    if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
496                        return i + 2;
497                    }
498                    if b == 0x1B || b < 0x20 {
499                        return i;
500                    }
501                    i += 1;
502                }
503            }
504            // Single-char escape sequences.
505            0x20..=0x7E => return i + 1,
506            _ => {}
507        }
508
509        i
510    }
511
512    fn decode_utf8_char(bytes: &[u8]) -> Option<(char, usize)> {
513        if bytes.is_empty() {
514            return None;
515        }
516
517        let first = bytes[0];
518        let (expected_len, mut codepoint) = match first {
519            0x00..=0x7F => return Some((first as char, 1)),
520            0xC0..=0xDF => (2, (first & 0x1F) as u32),
521            0xE0..=0xEF => (3, (first & 0x0F) as u32),
522            0xF0..=0xF7 => (4, (first & 0x07) as u32),
523            _ => return None,
524        };
525
526        if bytes.len() < expected_len {
527            return None;
528        }
529
530        for &b in bytes.iter().take(expected_len).skip(1) {
531            if (b & 0xC0) != 0x80 {
532                return None;
533            }
534            codepoint = (codepoint << 6) | (b & 0x3F) as u32;
535        }
536
537        let min_codepoint = match expected_len {
538            2 => 0x80,
539            3 => 0x800,
540            4 => 0x1_0000,
541            _ => return None,
542        };
543        if codepoint < min_codepoint {
544            return None;
545        }
546
547        char::from_u32(codepoint).map(|c| (c, expected_len))
548    }
549
550    /// Internal cleanup - guaranteed to run on drop.
551    fn cleanup_internal(&mut self) -> io::Result<()> {
552        let sync_output_enabled = self.sync_output_enabled();
553
554        // End any pending sync block
555        if self.in_sync_block {
556            if sync_output_enabled {
557                let _ = self.writer.write_all(SYNC_END);
558            }
559            self.in_sync_block = false;
560        }
561
562        // Reset scroll region if we set one
563        if self.scroll_region_set {
564            let _ = self.writer.write_all(RESET_SCROLL_REGION);
565            self.scroll_region_set = false;
566        }
567
568        // Restore cursor only if we saved it (avoid restoring to stale position)
569        if self.cursor_saved {
570            let _ = self.writer.write_all(CURSOR_RESTORE);
571            self.cursor_saved = false;
572        }
573
574        self.writer.flush()
575    }
576}
577
578/// Reduce arbitrary (already escape-sanitized or raw) text to at most one
579/// display line: everything from the first `\n`/`\r` onward is dropped,
580/// remaining control characters are skipped, and the result is truncated to
581/// `max_cols` terminal columns using Unicode display width.
582///
583/// Used by overlay-style inline logging ([`InlineRenderer::write_log`] and
584/// `TerminalWriter::write_log`) where emitting a newline would scroll (and
585/// corrupt) the displayed UI.
586pub fn sanitize_overlay_log_line(text: &str, max_cols: usize) -> String {
587    if max_cols == 0 {
588        return String::new();
589    }
590
591    let mut out = String::new();
592    let mut used_cols = 0usize;
593
594    // Measured per grapheme with the crate's own width, not by summing
595    // `UnicodeWidthChar` per scalar. The two disagree: a lone regional
596    // indicator is one column to `unicode-width` and two to every width
597    // function in this workspace, so the per-scalar sum let a two-column
598    // glyph into a one-column overlay — one column past the clamp whose
599    // entire purpose is to keep the line from wrapping into the UI.
600    for grapheme in text.graphemes(true) {
601        // One display line: `\r\n` is a single grapheme, so test the start.
602        if grapheme.starts_with('\n') || grapheme.starts_with('\r') {
603            break;
604        }
605
606        // Skip control characters so logs cannot inject cursor motion. A
607        // control is always its own grapheme.
608        if grapheme.chars().all(char::is_control) {
609            continue;
610        }
611
612        let width = crate::text_width::grapheme_width(grapheme);
613        if width == 0 {
614            // Keep a zero-width cluster only when it can attach to prior text.
615            if !out.is_empty() {
616                out.push_str(grapheme);
617            }
618            continue;
619        }
620
621        if used_cols.saturating_add(width) > max_cols {
622            break;
623        }
624
625        out.push_str(grapheme);
626        used_cols += width;
627        if used_cols == max_cols {
628            break;
629        }
630    }
631
632    out
633}
634
635impl<W: Write> Drop for InlineRenderer<W> {
636    fn drop(&mut self) {
637        // Best-effort cleanup on drop (including panic)
638        let _ = self.cleanup_internal();
639    }
640}
641
642// ============================================================================
643// Tests
644// ============================================================================
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649    use std::io::Cursor;
650
651    type TestWriter = Cursor<Vec<u8>>;
652
653    fn test_writer() -> TestWriter {
654        Cursor::new(Vec::new())
655    }
656
657    fn writer_contains_sequence(writer: &TestWriter, seq: &[u8]) -> bool {
658        writer
659            .get_ref()
660            .windows(seq.len())
661            .any(|window| window == seq)
662    }
663
664    fn writer_clear(writer: &mut TestWriter) {
665        writer.get_mut().clear();
666    }
667
668    fn sync_policy_allows() -> bool {
669        TerminalCapabilities::with_overrides().use_sync_output()
670    }
671
672    #[test]
673    fn config_calculates_regions_correctly() {
674        // 24 row terminal, 6 row UI
675        let config = InlineConfig::new(6, 24, 80);
676        assert_eq!(config.ui_top_row(), 19); // rows 19-24 are UI
677        assert_eq!(config.log_bottom_row(), 18); // rows 1-18 are logs
678    }
679
680    #[test]
681    fn strategy_selection_prefers_overlay_in_mux() {
682        let mut caps = TerminalCapabilities::basic();
683        caps.in_tmux = true;
684        caps.scroll_region = true;
685        caps.sync_output = true;
686
687        assert_eq!(InlineStrategy::select(&caps), InlineStrategy::OverlayRedraw);
688    }
689
690    #[test]
691    fn strategy_selection_uses_scroll_region_in_modern_terminal() {
692        let mut caps = TerminalCapabilities::basic();
693        caps.scroll_region = true;
694        caps.sync_output = true;
695
696        assert_eq!(InlineStrategy::select(&caps), InlineStrategy::ScrollRegion);
697    }
698
699    #[test]
700    fn strategy_selection_uses_hybrid_without_sync() {
701        let mut caps = TerminalCapabilities::basic();
702        caps.scroll_region = true;
703        caps.sync_output = false;
704
705        assert_eq!(InlineStrategy::select(&caps), InlineStrategy::Hybrid);
706    }
707
708    #[test]
709    fn enter_sets_scroll_region_for_scroll_strategy() {
710        let writer = test_writer();
711        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
712        let mut renderer = InlineRenderer::new(writer, config);
713
714        renderer.enter().unwrap();
715
716        // Should set scroll region: ESC [ 1 ; 18 r
717        assert!(writer_contains_sequence(&renderer.writer, b"\x1b[1;18r"));
718    }
719
720    #[test]
721    fn exit_resets_scroll_region() {
722        let writer = test_writer();
723        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
724        let mut renderer = InlineRenderer::new(writer, config);
725
726        renderer.enter().unwrap();
727        renderer.exit().unwrap();
728
729        // Should reset scroll region: ESC [ r
730        assert!(writer_contains_sequence(
731            &renderer.writer,
732            RESET_SCROLL_REGION
733        ));
734    }
735
736    #[test]
737    fn present_ui_saves_and_restores_cursor() {
738        let writer = test_writer();
739        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::OverlayRedraw);
740        let mut renderer = InlineRenderer::new(writer, config);
741
742        renderer
743            .present_ui(|w, _| {
744                w.write_all(b"UI Content")?;
745                Ok(())
746            })
747            .unwrap();
748
749        // Should save cursor (ESC 7)
750        assert!(writer_contains_sequence(&renderer.writer, CURSOR_SAVE));
751        // Should restore cursor (ESC 8)
752        assert!(writer_contains_sequence(&renderer.writer, CURSOR_RESTORE));
753    }
754
755    #[test]
756    fn present_ui_uses_sync_output_when_enabled() {
757        let writer = test_writer();
758        let config = InlineConfig::new(6, 24, 80)
759            .with_strategy(InlineStrategy::OverlayRedraw)
760            .with_sync_output(true);
761        let mut renderer = InlineRenderer::new(writer, config);
762
763        renderer.present_ui(|_, _| Ok(())).unwrap();
764
765        if sync_policy_allows() {
766            assert!(writer_contains_sequence(&renderer.writer, SYNC_BEGIN));
767            assert!(writer_contains_sequence(&renderer.writer, SYNC_END));
768        } else {
769            assert!(!writer_contains_sequence(&renderer.writer, SYNC_BEGIN));
770            assert!(!writer_contains_sequence(&renderer.writer, SYNC_END));
771        }
772    }
773
774    #[test]
775    fn drop_cleans_up_scroll_region() {
776        let writer = test_writer();
777        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
778
779        {
780            let mut renderer = InlineRenderer::new(writer, config);
781            renderer.enter().unwrap();
782            // Renderer dropped here
783        }
784
785        // Can't easily test drop output, but this verifies no panic
786    }
787
788    #[test]
789    fn write_log_preserves_cursor_in_overlay_mode() {
790        let writer = test_writer();
791        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::OverlayRedraw);
792        let mut renderer = InlineRenderer::new(writer, config);
793
794        renderer.write_log("test log\n").unwrap();
795
796        // Should save and restore cursor
797        assert!(writer_contains_sequence(&renderer.writer, CURSOR_SAVE));
798        assert!(writer_contains_sequence(&renderer.writer, CURSOR_RESTORE));
799    }
800
801    #[test]
802    fn write_log_overlay_truncates_to_single_safe_line() {
803        let writer = test_writer();
804        let config = InlineConfig::new(6, 24, 5).with_strategy(InlineStrategy::OverlayRedraw);
805        let mut renderer = InlineRenderer::new(writer, config);
806
807        renderer.write_log("ABCDE\nSECOND").unwrap();
808
809        let output = String::from_utf8_lossy(renderer.writer.get_ref());
810        assert!(output.contains("ABCDE"));
811        assert!(!output.contains("SECOND"));
812        assert!(!output.contains('\n'));
813    }
814
815    #[test]
816    fn write_log_overlay_truncates_wide_chars_by_display_width() {
817        let writer = test_writer();
818        let config = InlineConfig::new(6, 24, 3).with_strategy(InlineStrategy::OverlayRedraw);
819        let mut renderer = InlineRenderer::new(writer, config);
820
821        renderer.write_log("ab界Z").unwrap();
822
823        let output = String::from_utf8_lossy(renderer.writer.get_ref());
824        assert!(output.contains("ab"));
825        assert!(!output.contains('界'));
826        assert!(!output.contains('Z'));
827    }
828
829    #[test]
830    fn write_log_overlay_allows_wide_char_when_it_exactly_fits_width() {
831        let writer = test_writer();
832        let config = InlineConfig::new(6, 24, 4).with_strategy(InlineStrategy::OverlayRedraw);
833        let mut renderer = InlineRenderer::new(writer, config);
834
835        renderer.write_log("ab界Z").unwrap();
836
837        let output = String::from_utf8_lossy(renderer.writer.get_ref());
838        assert!(output.contains("ab界"));
839        assert!(!output.contains('Z'));
840    }
841
842    #[test]
843    fn hybrid_does_not_set_scroll_region_in_enter() {
844        let writer = test_writer();
845        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::Hybrid);
846        let mut renderer = InlineRenderer::new(writer, config);
847
848        renderer.enter().unwrap();
849
850        // Hybrid should NOT set scroll region (uses overlay baseline)
851        assert!(!writer_contains_sequence(&renderer.writer, b"\x1b[1;18r"));
852        assert!(!renderer.scroll_region_set);
853    }
854
855    #[test]
856    fn config_is_valid_checks_boundaries() {
857        // Valid config
858        let valid = InlineConfig::new(6, 24, 80);
859        assert!(valid.is_valid());
860
861        // UI takes all rows (no room for logs)
862        let full_ui = InlineConfig::new(24, 24, 80);
863        assert!(!full_ui.is_valid());
864
865        // Zero UI height
866        let no_ui = InlineConfig::new(0, 24, 80);
867        assert!(!no_ui.is_valid());
868
869        // Single row terminal
870        let tiny = InlineConfig::new(1, 1, 80);
871        assert!(!tiny.is_valid());
872    }
873
874    #[test]
875    fn log_bottom_row_zero_when_no_room() {
876        // UI takes full height
877        let config = InlineConfig::new(24, 24, 80);
878        assert_eq!(config.log_bottom_row(), 0);
879    }
880
881    #[test]
882    fn write_log_silently_drops_when_no_log_region() {
883        let writer = test_writer();
884        // UI takes full height - no room for logs
885        let config = InlineConfig::new(24, 24, 80).with_strategy(InlineStrategy::OverlayRedraw);
886        let mut renderer = InlineRenderer::new(writer, config);
887
888        // Should succeed but not write anything meaningful
889        renderer.write_log("test log\n").unwrap();
890
891        // Should not have written cursor save/restore since we bailed early
892        assert!(!writer_contains_sequence(&renderer.writer, CURSOR_SAVE));
893    }
894
895    #[test]
896    fn cleanup_does_not_restore_unsaved_cursor() {
897        let writer = test_writer();
898        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
899        let mut renderer = InlineRenderer::new(writer, config);
900
901        // Just enter and exit, never save cursor explicitly
902        renderer.enter().unwrap();
903        writer_clear(&mut renderer.writer); // Clear output to check cleanup behavior
904        renderer.exit().unwrap();
905
906        // Should NOT restore cursor since we never saved it
907        assert!(!writer_contains_sequence(&renderer.writer, CURSOR_RESTORE));
908    }
909
910    #[test]
911    fn inline_strategy_default_is_hybrid() {
912        assert_eq!(InlineStrategy::default(), InlineStrategy::Hybrid);
913    }
914
915    #[test]
916    fn config_ui_top_row_clamps_to_1() {
917        // ui_height >= term_height means saturating_sub yields 0, +1 = 1
918        let config = InlineConfig::new(30, 24, 80);
919        assert!(config.ui_top_row() >= 1);
920    }
921
922    #[test]
923    fn strategy_select_fallback_no_scroll_no_sync() {
924        let mut caps = TerminalCapabilities::basic();
925        caps.scroll_region = false;
926        caps.sync_output = false;
927        assert_eq!(InlineStrategy::select(&caps), InlineStrategy::OverlayRedraw);
928    }
929
930    #[test]
931    fn write_log_in_scroll_region_mode() {
932        let writer = test_writer();
933        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
934        let mut renderer = InlineRenderer::new(writer, config);
935
936        renderer.enter().unwrap();
937        renderer.write_log("hello\n").unwrap();
938
939        // In scroll-region mode, log is written directly without cursor save/restore
940        let output = renderer.writer.get_ref();
941        assert!(output.windows(b"hello\n".len()).any(|w| w == b"hello\n"));
942    }
943
944    #[test]
945    fn write_log_in_scroll_region_mode_sanitizes_escape_payloads() {
946        let writer = test_writer();
947        let config = InlineConfig::new(6, 24, 80).with_strategy(InlineStrategy::ScrollRegion);
948        let mut renderer = InlineRenderer::new(writer, config);
949
950        renderer.enter().unwrap();
951        renderer
952            .write_log("safe\x1b]52;c;SGVsbG8=\x1b\\tail\u{009d}x\n")
953            .unwrap();
954
955        let output = String::from_utf8_lossy(renderer.writer.get_ref());
956        assert!(output.contains("safetailx\n"));
957        assert!(
958            !output.contains("52;c;SGVsbG8"),
959            "OSC payload should not survive scroll-region log sanitization"
960        );
961        assert!(
962            !output.contains('\u{009d}'),
963            "C1 controls must be stripped in scroll-region logging"
964        );
965    }
966
967    #[test]
968    fn present_ui_clears_ui_lines() {
969        let writer = test_writer();
970        let config = InlineConfig::new(2, 10, 80).with_strategy(InlineStrategy::OverlayRedraw);
971        let mut renderer = InlineRenderer::new(writer, config);
972
973        renderer.present_ui(|_, _| Ok(())).unwrap();
974
975        // Should contain ERASE_LINE sequences for the 2 UI rows
976        let count = renderer
977            .writer
978            .get_ref()
979            .windows(ERASE_LINE.len())
980            .filter(|w| *w == ERASE_LINE)
981            .count();
982        assert_eq!(count, 2);
983    }
984
985    #[test]
986    fn present_ui_render_error_still_restores_state() {
987        let writer = test_writer();
988        let config = InlineConfig::new(2, 10, 80)
989            .with_strategy(InlineStrategy::OverlayRedraw)
990            .with_sync_output(true);
991        let mut renderer = InlineRenderer::new(writer, config);
992
993        let err = renderer
994            .present_ui(|_, _| Err(io::Error::other("boom")))
995            .unwrap_err();
996        assert_eq!(err.kind(), io::ErrorKind::Other);
997
998        assert!(writer_contains_sequence(&renderer.writer, CURSOR_RESTORE));
999        if sync_policy_allows() {
1000            assert!(writer_contains_sequence(&renderer.writer, SYNC_END));
1001        } else {
1002            assert!(!writer_contains_sequence(&renderer.writer, SYNC_END));
1003        }
1004        assert!(!renderer.cursor_saved);
1005        assert!(!renderer.in_sync_block);
1006    }
1007
1008    #[test]
1009    fn cleanup_skips_sync_end_when_sync_output_disabled() {
1010        let writer = test_writer();
1011        let config = InlineConfig::new(2, 10, 80)
1012            .with_strategy(InlineStrategy::OverlayRedraw)
1013            .with_sync_output(false);
1014        let mut renderer = InlineRenderer::new(writer, config);
1015        renderer.in_sync_block = true;
1016
1017        renderer.cleanup_internal().unwrap();
1018
1019        assert!(
1020            !writer_contains_sequence(&renderer.writer, SYNC_END),
1021            "sync_end must not be emitted when synchronized output is disabled"
1022        );
1023        assert!(!renderer.in_sync_block);
1024    }
1025
1026    #[test]
1027    fn present_ui_rejects_invalid_config() {
1028        let writer = test_writer();
1029        let config = InlineConfig::new(0, 24, 80).with_strategy(InlineStrategy::OverlayRedraw);
1030        let mut renderer = InlineRenderer::new(writer, config);
1031
1032        let err = renderer.present_ui(|_, _| Ok(())).unwrap_err();
1033        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1034        assert!(!writer_contains_sequence(&renderer.writer, CURSOR_SAVE));
1035    }
1036
1037    #[test]
1038    fn config_new_defaults() {
1039        let config = InlineConfig::new(5, 20, 100);
1040        assert_eq!(config.ui_height, 5);
1041        assert_eq!(config.term_height, 20);
1042        assert_eq!(config.term_width, 100);
1043        assert_eq!(config.strategy, InlineStrategy::Hybrid);
1044        assert!(!config.use_sync_output);
1045    }
1046
1047    /// The overlay clamp measured width by summing `UnicodeWidthChar` per
1048    /// scalar, which disagrees with every width function in this workspace on
1049    /// a lone regional indicator: one column there, two everywhere else. A
1050    /// two-column glyph therefore fit a one-column overlay, one past the
1051    /// clamp that exists to stop the line wrapping into the UI.
1052    #[test]
1053    fn the_overlay_clamp_measures_width_the_way_the_rest_of_the_crate_does() {
1054        let half_flag = "\u{1F1EB}";
1055        assert_eq!(crate::text_width::grapheme_width(half_flag), 2);
1056        assert_eq!(sanitize_overlay_log_line(half_flag, 1), "");
1057        assert_eq!(sanitize_overlay_log_line(half_flag, 2), half_flag);
1058
1059        // Whatever survives never exceeds the width it was clamped to.
1060        for text in [
1061            "\u{1F1EB}\u{1F1F7}",
1062            "\u{1F1EB}a",
1063            "中中中",
1064            "a\u{301}bc",
1065            "🦀🦀",
1066            "ab",
1067        ] {
1068            for cols in 0..8usize {
1069                let out = sanitize_overlay_log_line(text, cols);
1070                assert!(
1071                    crate::text_width::display_width(&out) <= cols,
1072                    "{text:?} at {cols} columns produced {out:?}"
1073                );
1074            }
1075        }
1076    }
1077
1078    /// The other half of the contract: one line, and nothing that can move
1079    /// the cursor.
1080    #[test]
1081    fn the_overlay_clamp_keeps_one_line_and_drops_cursor_motion() {
1082        assert_eq!(sanitize_overlay_log_line("a\nb", 40), "a");
1083        assert_eq!(sanitize_overlay_log_line("a\r\nb", 40), "a");
1084        assert_eq!(sanitize_overlay_log_line("a\u{1b}[2Jb\u{7}c", 40), "a[2Jbc");
1085        let out = sanitize_overlay_log_line("x\u{1b}[31my\nz", 40);
1086        assert!(
1087            !out.contains('\n') && !out.chars().any(char::is_control),
1088            "{out:?}"
1089        );
1090    }
1091}