Skip to main content

ftui_render/
presenter.rs

1#![forbid(unsafe_code)]
2
3//! Presenter: state-tracked ANSI emission.
4//!
5//! The Presenter transforms buffer diffs into minimal terminal output by tracking
6//! the current terminal state and only emitting sequences when changes are needed.
7//!
8//! # Design Principles
9//!
10//! - **State tracking**: Track current style, link, and cursor to avoid redundant output
11//! - **Run grouping**: Use ChangeRuns to minimize cursor positioning
12//! - **Single write**: Buffer all output and flush once per frame
13//! - **Synchronized output**: Use DEC 2026 to prevent flicker on supported terminals
14//!
15//! # Usage
16//!
17//! ```ignore
18//! use ftui_render::presenter::Presenter;
19//! use ftui_render::buffer::Buffer;
20//! use ftui_render::diff::BufferDiff;
21//! use ftui_core::terminal_capabilities::TerminalCapabilities;
22//!
23//! let caps = TerminalCapabilities::detect();
24//! let mut presenter = Presenter::new(std::io::stdout(), caps);
25//!
26//! let mut current = Buffer::new(80, 24);
27//! let mut next = Buffer::new(80, 24);
28//! // ... render widgets into `next` ...
29//!
30//! let diff = BufferDiff::compute(&current, &next);
31//! presenter.present(&next, &diff)?;
32//! std::mem::swap(&mut current, &mut next);
33//! ```
34
35use std::io::{self, BufWriter, Write};
36
37use crate::ansi::{self, EraseLineMode};
38use crate::buffer::Buffer;
39use crate::cell::{Cell, CellAttrs, GraphemeId, PackedRgba, StyleFlags};
40use crate::char_width;
41use crate::counting_writer::{CountingWriter, PresentStats, StatsCollector};
42use crate::diff::{BufferDiff, ChangeRun};
43use crate::display_width;
44use crate::grapheme_pool::GraphemePool;
45use crate::link_registry::LinkRegistry;
46use crate::sanitize::sanitize;
47
48pub use ftui_core::terminal_capabilities::{ColorDepth, TerminalCapabilities};
49
50/// Size of the internal write buffer (64KB).
51const BUFFER_CAPACITY: usize = 64 * 1024;
52/// Maximum hyperlink URL length allowed in OSC 8 payloads.
53const MAX_SAFE_HYPERLINK_URL_BYTES: usize = 4096;
54
55#[inline]
56fn is_safe_hyperlink_url(url: &str) -> bool {
57    url.len() <= MAX_SAFE_HYPERLINK_URL_BYTES && !url.chars().any(char::is_control)
58}
59
60// =============================================================================
61// DP Cost Model for ANSI Emission
62// =============================================================================
63
64/// Byte-cost estimates for ANSI cursor and output operations.
65///
66/// The cost model computes the cheapest emission plan for each row by comparing
67/// sparse-run emission (CUP per run) against merged write-through (one CUP,
68/// fill gaps with buffer content). This is a shortest-path problem on a small
69/// state graph per row.
70mod cost_model {
71    use smallvec::SmallVec;
72
73    use super::ChangeRun;
74
75    /// Number of decimal digits needed to represent `n`.
76    #[inline]
77    fn digit_count(n: u16) -> usize {
78        // Terminal coordinates and relative deltas are overwhelmingly small.
79        // Check the common low ranges first so the planner pays fewer compares
80        // on its hottest cost-model path.
81        if n < 10 {
82            1
83        } else if n < 100 {
84            2
85        } else if n < 1000 {
86            3
87        } else if n < 10000 {
88            4
89        } else {
90            5
91        }
92    }
93
94    /// Byte cost of CUP: `\x1b[{row+1};{col+1}H`
95    #[inline]
96    pub fn cup_cost(row: u16, col: u16) -> usize {
97        // CSI (2) + row digits + ';' (1) + col digits + 'H' (1)
98        4 + digit_count(row.saturating_add(1)) + digit_count(col.saturating_add(1))
99    }
100
101    /// Byte cost of CHA (column-only): `\x1b[{col+1}G`
102    #[inline]
103    pub fn cha_cost(col: u16) -> usize {
104        // CSI (2) + col digits + 'G' (1)
105        3 + digit_count(col.saturating_add(1))
106    }
107
108    /// Byte cost of CUF (cursor forward): `\x1b[{n}C` or `\x1b[C` for n=1.
109    #[inline]
110    pub fn cuf_cost(n: u16) -> usize {
111        match n {
112            0 => 0,
113            1 => 3, // \x1b[C
114            _ => 3 + digit_count(n),
115        }
116    }
117
118    /// Byte cost of CUB (cursor back): `\x1b[{n}D` or `\x1b[D` for n=1.
119    #[inline]
120    pub fn cub_cost(n: u16) -> usize {
121        match n {
122            0 => 0,
123            1 => 3, // \x1b[D
124            _ => 3 + digit_count(n),
125        }
126    }
127
128    /// Cheapest cursor movement cost from (from_x, from_y) to (to_x, to_y).
129    /// Returns 0 if already at the target position.
130    ///
131    /// Coordinates are viewport-relative. The CUP arm therefore estimates
132    /// the row field's digit count from the relative row, while emission
133    /// adds the presenter's viewport offset — in deep inline anchors the
134    /// physical row can carry more digits than estimated (~2 bytes per
135    /// cross-row move). This only skews sparse-vs-merged *planning*, never
136    /// the emitted coordinates, so the approximation is accepted instead of
137    /// threading the offset through the row DP.
138    pub fn cheapest_move_cost(
139        from_x: Option<u16>,
140        from_y: Option<u16>,
141        to_x: u16,
142        to_y: u16,
143    ) -> usize {
144        // Already at target?
145        if from_x == Some(to_x) && from_y == Some(to_y) {
146            return 0;
147        }
148
149        match (from_x, from_y) {
150            (Some(fx), Some(fy)) if fy == to_y => {
151                // On the same row, CHA strictly dominates CUP because CUP always
152                // pays the extra row field (`CSI row;col H`) while CHA only
153                // updates the column (`CSI col G`). Therefore the optimal move
154                // on a shared row is always CHA or a relative move.
155                let cha = cha_cost(to_x);
156                if to_x > fx {
157                    let cuf = cuf_cost(to_x - fx);
158                    cha.min(cuf)
159                } else if to_x < fx {
160                    let cub = cub_cost(fx - to_x);
161                    cha.min(cub)
162                } else {
163                    0
164                }
165            }
166            _ => cup_cost(to_y, to_x),
167        }
168    }
169
170    /// Planned contiguous span to emit on a single row.
171    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
172    pub struct RowSpan {
173        /// Row index.
174        pub y: u16,
175        /// Start column (inclusive).
176        pub x0: u16,
177        /// End column (inclusive).
178        pub x1: u16,
179    }
180
181    /// Row emission plan (possibly multiple merged spans).
182    ///
183    /// Uses SmallVec<[RowSpan; 8]> to avoid heap allocation for the common case
184    /// of sparse rows with several isolated runs. RowSpan is 6 bytes, so
185    /// 8 spans = 48 bytes inline.
186    #[derive(Debug, Clone, PartialEq, Eq)]
187    pub struct RowPlan {
188        spans: SmallVec<[RowSpan; 8]>,
189        total_cost: usize,
190    }
191
192    impl RowPlan {
193        #[inline]
194        #[must_use]
195        pub fn spans(&self) -> &[RowSpan] {
196            &self.spans
197        }
198
199        /// Total cost of this row plan (for strategy selection).
200        #[inline]
201        #[allow(dead_code)] // API for future diff strategy integration
202        pub fn total_cost(&self) -> usize {
203            self.total_cost
204        }
205    }
206
207    /// Reusable scratch buffers for `plan_row_reuse`, avoiding per-call heap
208    /// allocations. Store one instance in `Presenter` and pass it into every
209    /// `plan_row_reuse` call so that the buffers are reused across rows and
210    /// frames.
211    #[derive(Debug, Default)]
212    pub struct RowPlanScratch {
213        prefix_cells: Vec<usize>,
214        dp: Vec<usize>,
215        prev: Vec<usize>,
216    }
217
218    /// Compute the optimal emission plan for a set of runs on the same row.
219    ///
220    /// This is a shortest-path / DP partitioning problem over contiguous run
221    /// segments. Each segment may be emitted as a merged span (writing through
222    /// gaps). Single-run segments correspond to sparse emission.
223    ///
224    /// Gap cells cost ~1 byte each (character content), plus potential style
225    /// overhead estimated at 1 byte per gap cell (conservative).
226    #[allow(dead_code)]
227    pub fn plan_row(row_runs: &[ChangeRun], prev_x: Option<u16>, prev_y: Option<u16>) -> RowPlan {
228        let mut scratch = RowPlanScratch::default();
229        plan_row_reuse(row_runs, prev_x, prev_y, &mut scratch)
230    }
231
232    /// Like `plan_row` but reuses heap allocations via the provided scratch
233    /// buffers, eliminating per-call allocations in the hot path.
234    pub fn plan_row_reuse(
235        row_runs: &[ChangeRun],
236        prev_x: Option<u16>,
237        prev_y: Option<u16>,
238        scratch: &mut RowPlanScratch,
239    ) -> RowPlan {
240        if row_runs.is_empty() {
241            return RowPlan {
242                spans: SmallVec::new(),
243                total_cost: 0,
244            };
245        }
246
247        let row_y = row_runs[0].y;
248        let run_count = row_runs.len();
249
250        if run_count == 1 {
251            let run = row_runs[0];
252            let mut spans: SmallVec<[RowSpan; 8]> = SmallVec::new();
253            spans.push(RowSpan {
254                y: row_y,
255                x0: run.x0,
256                x1: run.x1,
257            });
258            return RowPlan {
259                spans,
260                total_cost: cheapest_move_cost(prev_x, prev_y, run.x0, row_y)
261                    .saturating_add(run.len()),
262            };
263        }
264
265        // Resize scratch buffers (no-op if already large enough).
266        scratch.prefix_cells.clear();
267        scratch.prefix_cells.resize(run_count + 1, 0);
268        scratch.dp.clear();
269        scratch.dp.resize(run_count, usize::MAX);
270        scratch.prev.clear();
271        scratch.prev.resize(run_count, 0);
272
273        // Prefix sum of changed cell counts for O(1) segment cost.
274        for (i, run) in row_runs.iter().enumerate() {
275            scratch.prefix_cells[i + 1] = scratch.prefix_cells[i] + run.len();
276        }
277
278        // DP over segments: dp[j] is min cost to emit runs[0..=j].
279        for j in 0..run_count {
280            let mut best_cost = usize::MAX;
281            let mut best_i = j;
282
283            // Optimization: iterate backwards and break if the gap becomes too large.
284            // The gap cost grows linearly, while cursor movement cost is bounded (~10-15 bytes).
285            // Once the gap exceeds ~20 cells, merging is strictly worse than moving.
286            // We use 32 as a conservative safety bound.
287            for i in (0..=j).rev() {
288                let changed_cells = scratch.prefix_cells[j + 1] - scratch.prefix_cells[i];
289                let total_cells =
290                    (row_runs[j].x1 as usize).saturating_sub(row_runs[i].x0 as usize) + 1;
291                let gap_cells = total_cells.saturating_sub(changed_cells);
292
293                if gap_cells > 32 {
294                    break;
295                }
296
297                let from_x = if i == 0 {
298                    prev_x
299                } else {
300                    Some(row_runs[i - 1].x1.saturating_add(1))
301                };
302                let from_y = if i == 0 { prev_y } else { Some(row_y) };
303
304                let move_cost = cheapest_move_cost(from_x, from_y, row_runs[i].x0, row_y);
305                let gap_overhead = gap_cells * 2; // conservative: char + style amortized
306                let emit_cost = changed_cells + gap_overhead;
307
308                let prev_cost = if i == 0 { 0 } else { scratch.dp[i - 1] };
309                let cost = prev_cost
310                    .saturating_add(move_cost)
311                    .saturating_add(emit_cost);
312
313                if cost < best_cost {
314                    best_cost = cost;
315                    best_i = i;
316                }
317            }
318
319            scratch.dp[j] = best_cost;
320            scratch.prev[j] = best_i;
321        }
322
323        // Reconstruct spans from back to front.
324        let mut spans: SmallVec<[RowSpan; 8]> = SmallVec::new();
325        let mut j = run_count - 1;
326        loop {
327            let i = scratch.prev[j];
328            spans.push(RowSpan {
329                y: row_y,
330                x0: row_runs[i].x0,
331                x1: row_runs[j].x1,
332            });
333            if i == 0 {
334                break;
335            }
336            j = i - 1;
337        }
338        spans.reverse();
339
340        RowPlan {
341            spans,
342            total_cost: scratch.dp[run_count - 1],
343        }
344    }
345}
346
347/// Cached style state for comparison.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349struct CellStyle {
350    fg: PackedRgba,
351    bg: PackedRgba,
352    attrs: StyleFlags,
353}
354
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356enum PreparedContent {
357    Empty,
358    Char(char),
359    Grapheme(GraphemeId),
360}
361
362impl PreparedContent {
363    #[inline]
364    fn from_cell(cell: &Cell) -> (Self, usize) {
365        let content = cell.content;
366        if let Some(grapheme_id) = content.grapheme_id() {
367            (Self::Grapheme(grapheme_id), content.width())
368        } else if let Some(ch) = content.as_char() {
369            let width = if ch.is_ascii() {
370                match ch {
371                    '\t' | '\n' | '\r' => 1,
372                    ' '..='~' => 1,
373                    _ => 0,
374                }
375            } else {
376                char_width(ch)
377            };
378            (Self::Char(ch), width)
379        } else {
380            (Self::Empty, 0)
381        }
382    }
383}
384
385impl Default for CellStyle {
386    fn default() -> Self {
387        Self {
388            fg: PackedRgba::TRANSPARENT,
389            bg: PackedRgba::TRANSPARENT,
390            attrs: StyleFlags::empty(),
391        }
392    }
393}
394impl CellStyle {
395    fn from_cell(cell: &Cell) -> Self {
396        Self {
397            fg: cell.fg,
398            bg: cell.bg,
399            attrs: cell.attrs.flags(),
400        }
401    }
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
405enum ResolvedColor {
406    Suppressed,
407    Default,
408    Ansi16(u8),
409    Ansi256(u8),
410    TrueColor(u8, u8, u8),
411}
412
413/// State-tracked ANSI presenter.
414///
415/// Transforms buffer diffs into minimal terminal output by tracking
416/// the current terminal state and only emitting necessary escape sequences.
417pub struct Presenter<W: Write> {
418    /// Buffered writer for efficient output, with byte counting.
419    writer: CountingWriter<BufWriter<W>>,
420    /// Current style state (None = unknown/reset).
421    current_style: Option<CellStyle>,
422    /// Current hyperlink ID (None = no link).
423    current_link: Option<u32>,
424    /// Current cursor X position (0-indexed). None = unknown.
425    cursor_x: Option<u16>,
426    /// Current cursor Y position (0-indexed). None = unknown.
427    cursor_y: Option<u16>,
428    /// Viewport Y offset (added to all row coordinates).
429    viewport_offset_y: u16,
430    /// Rows from the viewport's top row to the terminal's last row, when rows
431    /// are addressed from the bottom instead (see `set_viewport_bottom`).
432    viewport_bottom: Option<u16>,
433    /// Terminal capabilities for conditional output.
434    capabilities: TerminalCapabilities,
435    /// Cached hyperlink policy for the lifetime of this presenter.
436    hyperlinks_enabled: bool,
437    /// Reusable scratch buffers for the cost-model DP, avoiding per-row
438    /// heap allocations in the hot presentation path.
439    plan_scratch: cost_model::RowPlanScratch,
440    /// Reusable buffer for change runs, avoiding per-frame allocation.
441    runs_buf: Vec<ChangeRun>,
442    /// Width of the buffer being presented (0 = unknown). Used to invalidate
443    /// the tracked cursor column when output reaches the last column, where a
444    /// real autowrap terminal parks in wrap-pending state instead of
445    /// advancing — relative moves from the phantom column would be off by one.
446    presentation_width: u16,
447}
448
449impl<W: Write> Presenter<W> {
450    /// Create a new presenter with the given writer and capabilities.
451    pub fn new(writer: W, capabilities: TerminalCapabilities) -> Self {
452        Self {
453            writer: CountingWriter::new(BufWriter::with_capacity(BUFFER_CAPACITY, writer)),
454            current_style: None,
455            current_link: None,
456            cursor_x: None,
457            cursor_y: None,
458            viewport_offset_y: 0,
459            viewport_bottom: None,
460            hyperlinks_enabled: capabilities.use_hyperlinks(),
461            capabilities,
462            plan_scratch: cost_model::RowPlanScratch::default(),
463            runs_buf: Vec::new(),
464            presentation_width: 0,
465        }
466    }
467
468    /// Get mutable access to the innermost writer (`W`).
469    ///
470    /// This allows the caller to write raw data (e.g. logs) bypassing the
471    /// presenter's state tracking. Note that this may invalidate cursor
472    /// tracking if the raw writes move the cursor.
473    pub fn writer_mut(&mut self) -> &mut W {
474        self.writer.inner_mut().get_mut()
475    }
476
477    /// Get mutable access to the full counting writer stack.
478    ///
479    /// This exposes `CountingWriter<BufWriter<W>>` so callers can access
480    /// byte counting, buffered flush, etc.
481    pub fn counting_writer_mut(&mut self) -> &mut CountingWriter<BufWriter<W>> {
482        &mut self.writer
483    }
484
485    /// Set the viewport Y offset.
486    ///
487    /// All subsequent render operations will add this offset to row coordinates.
488    /// Useful for inline mode where the UI starts at a specific row.
489    pub fn set_viewport_offset_y(&mut self, offset: u16) {
490        self.viewport_offset_y = offset;
491    }
492
493    /// Address rows from the terminal's last row instead of its first.
494    ///
495    /// With `Some(rows)`, the viewport is the terminal's last `rows` rows and
496    /// row `y` is reached with [`ansi::cup_from_bottom`] (`rows - 1 - y` rows
497    /// above the last row), so a bottom-anchored region is drawn on the right
498    /// rows even if the terminal's height changed after the caller last
499    /// learned it. `None` restores [`Self::set_viewport_offset_y`] addressing.
500    pub fn set_viewport_bottom(&mut self, rows: Option<u16>) {
501        self.viewport_bottom = rows;
502    }
503
504    /// Absolute move to viewport row `y`, column `x` (0-indexed).
505    fn cup_row(&mut self, y: u16, x: u16) -> io::Result<()> {
506        match self.viewport_bottom {
507            Some(rows) => ansi::cup_from_bottom(
508                &mut self.writer,
509                rows.saturating_sub(1).saturating_sub(y),
510                x,
511            ),
512            None => ansi::cup(
513                &mut self.writer,
514                y.saturating_add(self.viewport_offset_y),
515                x,
516            ),
517        }
518    }
519
520    /// Get the terminal capabilities.
521    #[inline]
522    pub fn capabilities(&self) -> &TerminalCapabilities {
523        &self.capabilities
524    }
525
526    /// Present a frame using the given buffer and diff.
527    ///
528    /// This is the main entry point for rendering. It:
529    /// 1. Begins synchronized output (if supported)
530    /// 2. Emits changes based on the diff
531    /// 3. Resets style and closes links
532    /// 4. Ends synchronized output
533    /// 5. Flushes all buffered output
534    pub fn present(&mut self, buffer: &Buffer, diff: &BufferDiff) -> io::Result<PresentStats> {
535        self.present_with_pool(buffer, diff, None, None)
536    }
537
538    /// Present a frame with grapheme pool and link registry.
539    pub fn present_with_pool(
540        &mut self,
541        buffer: &Buffer,
542        diff: &BufferDiff,
543        pool: Option<&GraphemePool>,
544        links: Option<&LinkRegistry>,
545    ) -> io::Result<PresentStats> {
546        self.presentation_width = buffer.width();
547        let bracket_supported = self.capabilities.use_sync_output();
548
549        #[cfg(feature = "tracing")]
550        let _span = tracing::info_span!(
551            "present",
552            width = buffer.width(),
553            height = buffer.height(),
554            changes = diff.len()
555        );
556        #[cfg(feature = "tracing")]
557        let _guard = _span.enter();
558
559        #[cfg(feature = "tracing")]
560        let fallback_used = !bracket_supported;
561        #[cfg(feature = "tracing")]
562        let _sync_span = tracing::info_span!(
563            "render.sync_bracket",
564            bracket_supported,
565            fallback_used,
566            frame_bytes = tracing::field::Empty,
567        );
568        #[cfg(feature = "tracing")]
569        let _sync_guard = _sync_span.enter();
570
571        // Calculate runs upfront for stats, reusing the runs buffer.
572        diff.runs_into(&mut self.runs_buf);
573        let run_count = self.runs_buf.len();
574        let cells_changed = diff.len();
575
576        // Start stats collection
577        self.writer.reset_counter();
578        let collector = StatsCollector::start(cells_changed, run_count);
579
580        // Begin synchronized output to prevent flicker.
581        // When sync brackets are supported, use DEC 2026 for atomic frame display.
582        // Otherwise, fall back to cursor-hiding to reduce visual flicker.
583        if bracket_supported {
584            if let Err(err) = ansi::sync_begin(&mut self.writer) {
585                // Begin writes can fail after partial bytes; best-effort close
586                // avoids leaving the terminal parser in sync-output mode.
587                let _ = ansi::sync_end(&mut self.writer);
588                let _ = self.writer.flush();
589                return Err(err);
590            }
591        } else {
592            #[cfg(feature = "tracing")]
593            tracing::warn!("sync brackets unsupported; falling back to cursor-hide strategy");
594            ansi::cursor_hide(&mut self.writer)?;
595        }
596
597        // Emit diff using run grouping for efficiency.
598        let emit_result = self.emit_diff_runs(buffer, pool, links);
599
600        // Always attempt to restore terminal state, even if diff emission failed.
601        let frame_end_result = self.finish_frame();
602
603        let bracket_end_result = if bracket_supported {
604            ansi::sync_end(&mut self.writer)
605        } else {
606            ansi::cursor_show(&mut self.writer)
607        };
608
609        let flush_result = self.writer.flush();
610
611        // Prioritize terminal-state restoration errors over emission errors:
612        // if cleanup fails (reset/link-close/sync-end/flush), callers need that
613        // failure surfaced immediately to avoid leaving the terminal wedged.
614        let cleanup_error = frame_end_result
615            .err()
616            .or_else(|| bracket_end_result.err())
617            .or_else(|| flush_result.err());
618        if let Some(err) = cleanup_error {
619            return Err(err);
620        }
621        emit_result?;
622
623        let stats = collector.finish(self.writer.bytes_written());
624
625        #[cfg(feature = "tracing")]
626        {
627            _sync_span.record("frame_bytes", stats.bytes_emitted);
628            stats.log();
629            tracing::trace!("frame presented");
630        }
631
632        Ok(stats)
633    }
634
635    /// Emit diff runs using the cost model and internal buffers.
636    ///
637    /// This allows advanced callers (like TerminalWriter) to drive the emission
638    /// phase manually while still benefiting from the optimization logic.
639    /// The caller must populate `self.runs_buf` before calling this (e.g. via `diff.runs_into`).
640    pub fn emit_diff_runs(
641        &mut self,
642        buffer: &Buffer,
643        pool: Option<&GraphemePool>,
644        links: Option<&LinkRegistry>,
645    ) -> io::Result<()> {
646        // Arm the wrap-pending safeguard for this externally driven entry
647        // point too (present_with_pool sets it on its own path). Without
648        // this, advance_or_invalidate never invalidates the tracked column
649        // at the last cell, and the drift-repair paths can issue relative
650        // moves from a phantom column that a real autowrap terminal (parked
651        // in wrap-pending state) never reached.
652        self.presentation_width = buffer.width();
653
654        #[cfg(feature = "tracing")]
655        let _span = tracing::debug_span!("emit_diff");
656        #[cfg(feature = "tracing")]
657        let _guard = _span.enter();
658
659        #[cfg(feature = "tracing")]
660        tracing::trace!(run_count = self.runs_buf.len(), "emitting runs (reuse)");
661
662        // Group runs by row and apply cost model per row
663        let mut i = 0;
664        while i < self.runs_buf.len() {
665            let row_y = self.runs_buf[i].y;
666
667            // Collect all runs on this row
668            let row_start = i;
669            while i < self.runs_buf.len() && self.runs_buf[i].y == row_y {
670                i += 1;
671            }
672            let row_runs = &self.runs_buf[row_start..i];
673
674            if row_runs.len() == 1 {
675                let run = row_runs[0];
676
677                #[cfg(feature = "tracing")]
678                tracing::trace!(
679                    row = row_y,
680                    spans = 1,
681                    cost =
682                        cost_model::cheapest_move_cost(self.cursor_x, self.cursor_y, run.x0, row_y)
683                            .saturating_add(run.len()),
684                    "row plan single-run fast path"
685                );
686
687                let row = buffer.row_cells(row_y);
688                self.emit_row_span(row, run.y, run.x0, run.x1, pool, links)?;
689                continue;
690            }
691
692            let plan = cost_model::plan_row_reuse(
693                row_runs,
694                self.cursor_x,
695                self.cursor_y,
696                &mut self.plan_scratch,
697            );
698
699            #[cfg(feature = "tracing")]
700            tracing::trace!(
701                row = row_y,
702                spans = plan.spans().len(),
703                cost = plan.total_cost(),
704                "row plan"
705            );
706
707            let row = buffer.row_cells(row_y);
708            for span in plan.spans() {
709                self.emit_row_span(row, span.y, span.x0, span.x1, pool, links)?;
710            }
711        }
712        Ok(())
713    }
714
715    #[inline]
716    fn emit_row_span(
717        &mut self,
718        row: &[Cell],
719        y: u16,
720        x0: u16,
721        x1: u16,
722        pool: Option<&GraphemePool>,
723        links: Option<&LinkRegistry>,
724    ) -> io::Result<()> {
725        self.move_cursor_optimal(x0, y)?;
726        // Hot path: avoid recomputing `y * width + x` for every cell.
727        let start = x0 as usize;
728        let end = x1 as usize;
729        debug_assert!(start <= end);
730        debug_assert!(end < row.len());
731        let mut idx = start;
732        while idx <= end {
733            let cell = &row[idx];
734            self.emit_cell(idx as u16, cell, pool, links)?;
735
736            // Repair invalid wide-char tails.
737            //
738            // Direct wide chars are always safe to repair because they can
739            // only span a small, fixed number of cells. Grapheme-pool refs
740            // may encode much wider payloads (up to 15 cells), so blindly
741            // repairing all missing tails can erase unrelated content later in
742            // the row. We only extend the repair to width-2 grapheme refs,
743            // where clearing a single orphan tail cell is still bounded.
744            let mut advance = 1usize;
745            let width = cell.content.width();
746            let should_repair_invalid_tail =
747                cell.content.as_char().is_some() || (cell.content.is_grapheme() && width == 2);
748            if width > 1 && should_repair_invalid_tail {
749                for off in 1..width {
750                    let tx = idx + off;
751                    if tx >= row.len() {
752                        break;
753                    }
754                    if row[tx].is_continuation() {
755                        if tx <= end {
756                            advance = advance.max(off + 1);
757                        }
758                        continue;
759                    }
760                    // Orphan detected: repair with a space.
761                    self.move_cursor_optimal(tx as u16, y)?;
762                    self.emit_orphan_continuation_space(tx as u16, links)?;
763                    if tx <= end {
764                        advance = advance.max(off + 1);
765                    }
766                }
767            }
768
769            idx = idx.saturating_add(advance);
770        }
771
772        Ok(())
773    }
774
775    /// Prepare the runs buffer from a diff.
776    ///
777    /// Helper for external callers to populate the runs buffer before calling `emit_diff_runs`.
778    pub fn prepare_runs(&mut self, diff: &BufferDiff) {
779        diff.runs_into(&mut self.runs_buf);
780    }
781
782    /// Drop prepared runs on rows at or below `max_rows`.
783    ///
784    /// Inline-mode callers use this when the physical terminal is shorter
785    /// than the UI buffer: rows below the fold must not be emitted at all —
786    /// a real terminal clamps the CUP row to its bottom line, so emitting
787    /// them scribbles over the last visible row.
788    pub fn clip_runs_below(&mut self, max_rows: u16) {
789        self.runs_buf.retain(|run| run.y < max_rows);
790    }
791
792    /// Trim prepared runs on each row `y` to the occupied width `row_widths[y]`,
793    /// omitting trailing uncolored blank cells (`x >= row_widths[y]`).
794    ///
795    /// When `el_rows` is `Some` (incremental diff or un-cleared full redraw),
796    /// any row where a run reached into `[row_widths[y], width)` is recorded as
797    /// `(y, row_widths[y])` so the caller can emit `EL` (`\x1b[K`) at the new
798    /// end of the row instead of writing trailing spaces that terminal
799    /// multiplexers reflow as occupied columns.
800    pub fn trim_runs_to_row_widths(
801        &mut self,
802        row_widths: &[u16],
803        mut el_rows: Option<&mut Vec<(u16, u16)>>,
804    ) {
805        self.runs_buf.retain_mut(|run| {
806            let Some(&occ) = row_widths.get(usize::from(run.y)) else {
807                return true;
808            };
809            if run.x1 >= occ {
810                if let Some(el) = el_rows.as_deref_mut()
811                    && el.last().map(|&(ry, _)| ry) != Some(run.y)
812                {
813                    el.push((run.y, occ));
814                }
815                if occ == 0 || run.x0 >= occ {
816                    return false;
817                }
818                run.x1 = occ - 1;
819            }
820            true
821        });
822    }
823
824    /// Finish a frame by restoring neutral SGR state and closing any open link.
825    ///
826    /// Callers that drive emission manually through `emit_diff_runs` must
827    /// invoke this before returning control to non-UI terminal output.
828    pub fn finish_frame(&mut self) -> io::Result<()> {
829        let reset_result = ansi::sgr_reset(&mut self.writer);
830        self.current_style = None;
831
832        let hyperlink_close_result = if self.current_link.is_some() {
833            let res = ansi::hyperlink_end(&mut self.writer);
834            if res.is_ok() {
835                self.current_link = None;
836            }
837            Some(res)
838        } else {
839            None
840        };
841
842        if let Some(err) = reset_result
843            .err()
844            .or_else(|| hyperlink_close_result.and_then(Result::err))
845        {
846            return Err(err);
847        }
848
849        Ok(())
850    }
851
852    /// Best-effort frame cleanup used on error and drop paths.
853    pub fn finish_frame_best_effort(&mut self) {
854        let _ = ansi::sgr_reset(&mut self.writer);
855        self.current_style = None;
856
857        if self.current_link.is_some() {
858            let _ = ansi::hyperlink_end(&mut self.writer);
859            self.current_link = None;
860        }
861    }
862
863    /// Emit a single cell.
864    fn emit_cell(
865        &mut self,
866        x: u16,
867        cell: &Cell,
868        pool: Option<&GraphemePool>,
869        links: Option<&LinkRegistry>,
870    ) -> io::Result<()> {
871        // Drift protection: Ensure cursor is synchronized before emitting content.
872        // This catches cases where the previous emission (e.g. a wide char) advanced
873        // the cursor further than the buffer index advanced (e.g. because the
874        // continuation cell was missing/overwritten in an invalid buffer state).
875        //
876        // If we detect drift, we force a re-synchronization.
877        if let Some(cx) = self.cursor_x {
878            if cx != x && !cell.is_continuation() {
879                // Re-sync. We assume cursor_y is set because we are in a run.
880                if let Some(y) = self.cursor_y {
881                    self.move_cursor_optimal(x, y)?;
882                }
883            }
884        } else {
885            // No known cursor position: must sync.
886            if let Some(y) = self.cursor_y {
887                self.move_cursor_optimal(x, y)?;
888            }
889        }
890
891        // Continuation cells are the tail cells of wide glyphs. Emitting the
892        // head glyph already advanced the terminal cursor by the full width, so
893        // we normally skip emitting these cells.
894        //
895        // If we ever start emitting at a continuation cell (e.g. a run begins
896        // mid-wide-character), we must still advance the terminal cursor by one
897        // cell to keep subsequent emissions aligned. We write a space to clear
898        // any potential garbage (orphan cleanup) rather than just skipping with CUF.
899        if cell.is_continuation() {
900            match self.cursor_x {
901                // Cursor already advanced past this cell by a previously-emitted wide head.
902                Some(cx) if cx > x => return Ok(()),
903                Some(cx) => {
904                    // Cursor is positioned at (or before) this continuation cell:
905                    // Treat as orphan and overwrite with space to ensure clean state.
906                    if cx < x
907                        && let Some(y) = self.cursor_y
908                    {
909                        self.move_cursor_optimal(x, y)?;
910                    }
911                    return self.emit_orphan_continuation_space(x, links);
912                }
913                // Defensive: move_cursor_optimal should always set cursor_x before emit_cell is called.
914                None => {
915                    if let Some(y) = self.cursor_y {
916                        self.move_cursor_optimal(x, y)?;
917                    }
918                    return self.emit_orphan_continuation_space(x, links);
919                }
920            }
921        }
922
923        // Emit style changes if needed
924        self.emit_style_changes(cell)?;
925
926        // Emit link changes if needed
927        self.emit_link_changes(cell, links)?;
928
929        let (prepared_content, raw_width) = PreparedContent::from_cell(cell);
930
931        // Calculate effective width and check for zero-width content (e.g. combining marks)
932        // stored as standalone cells. These must be replaced to maintain grid alignment.
933        let is_zero_width_content = raw_width == 0 && !cell.is_empty() && !cell.is_continuation();
934
935        if is_zero_width_content {
936            // Replace with U+FFFD Replacement Character (width 1)
937            self.writer.write_all(b"\xEF\xBF\xBD")?;
938        } else {
939            // Emit normal content
940            self.emit_content(prepared_content, raw_width, pool)?;
941        }
942
943        // Update cursor position (character output advances cursor)
944        if let Some(cx) = self.cursor_x {
945            // Empty cells are emitted as spaces (width 1).
946            // Zero-width content replaced by U+FFFD is width 1.
947            let width = if cell.is_empty() || is_zero_width_content {
948                1
949            } else {
950                raw_width
951            };
952            self.cursor_x = Self::advance_or_invalidate(cx, width as u16, self.presentation_width);
953        }
954
955        Ok(())
956    }
957
958    /// Advance the tracked cursor column, invalidating it when the advance
959    /// reaches or passes the presentation width.
960    ///
961    /// A real terminal with autowrap (DECAWM, which is never disabled) does
962    /// NOT advance past the last column — it parks in wrap-pending state at
963    /// `width - 1`. Trusting the phantom `width` column would make the next
964    /// same-row relative move (CUF/CUB) land one column off, so the next
965    /// positioning must be forced absolute (CUP/CHA).
966    fn advance_or_invalidate(cx: u16, width: u16, presentation_width: u16) -> Option<u16> {
967        let next = cx.saturating_add(width);
968        if presentation_width > 0 && next >= presentation_width {
969            None
970        } else {
971            Some(next)
972        }
973    }
974
975    /// Clear a continuation cell with a visually neutral blank.
976    ///
977    /// This path intentionally resets style and closes hyperlinks first so the
978    /// cleanup space cannot inherit stale state from the previous emitted cell.
979    fn emit_orphan_continuation_space(
980        &mut self,
981        x: u16,
982        links: Option<&LinkRegistry>,
983    ) -> io::Result<()> {
984        let blank = Cell::default();
985        self.emit_style_changes(&blank)?;
986        self.emit_link_changes(&blank, links)?;
987        self.writer.write_all(b" ")?;
988        self.cursor_x = Self::advance_or_invalidate(x, 1, self.presentation_width);
989        Ok(())
990    }
991
992    /// Emit style changes if the cell style differs from current.
993    ///
994    /// Uses SGR delta: instead of resetting and re-applying all style properties,
995    /// we compute the minimal set of changes needed (fg delta, bg delta, attr
996    /// toggles). Falls back to reset+apply only when a full reset would be cheaper.
997    fn emit_style_changes(&mut self, cell: &Cell) -> io::Result<()> {
998        let new_style = CellStyle::from_cell(cell);
999
1000        // Check if style changed
1001        if self
1002            .current_style
1003            .is_some_and(|current| self.styles_equivalent(current, new_style))
1004        {
1005            return Ok(());
1006        }
1007
1008        match self.current_style {
1009            None => {
1010                // No known style state: re-establish a full terminal style baseline.
1011                self.emit_style_full(new_style)?;
1012            }
1013            Some(old_style) => {
1014                self.emit_style_delta(old_style, new_style)?;
1015            }
1016        }
1017
1018        self.current_style = Some(new_style);
1019        Ok(())
1020    }
1021
1022    /// Full style apply (reset + set all properties). Used when previous state is unknown.
1023    fn emit_style_full(&mut self, style: CellStyle) -> io::Result<()> {
1024        ansi::sgr_reset(&mut self.writer)?;
1025        let fg = self.resolve_color(style.fg);
1026        if !matches!(fg, ResolvedColor::Default | ResolvedColor::Suppressed) {
1027            self.emit_foreground(fg)?;
1028        }
1029        let bg = self.resolve_color(style.bg);
1030        if !matches!(bg, ResolvedColor::Default | ResolvedColor::Suppressed) {
1031            self.emit_background(bg)?;
1032        }
1033        if !style.attrs.is_empty() {
1034            ansi::sgr_flags(&mut self.writer, style.attrs)?;
1035        }
1036        Ok(())
1037    }
1038
1039    #[inline]
1040    fn resolve_color(&self, color: PackedRgba) -> ResolvedColor {
1041        if self.capabilities.color_depth == ColorDepth::Mono {
1042            return ResolvedColor::Suppressed;
1043        }
1044        if color.a() == 0 {
1045            return ResolvedColor::Default;
1046        }
1047
1048        match self.capabilities.color_depth {
1049            ColorDepth::Mono => ResolvedColor::Suppressed,
1050            ColorDepth::Ansi16 => {
1051                ResolvedColor::Ansi16(ansi::rgb_to_ansi16(color.r(), color.g(), color.b()))
1052            }
1053            ColorDepth::Ansi256 => {
1054                ResolvedColor::Ansi256(ansi::rgb_to_ansi256(color.r(), color.g(), color.b()))
1055            }
1056            ColorDepth::TrueColor => ResolvedColor::TrueColor(color.r(), color.g(), color.b()),
1057        }
1058    }
1059
1060    #[inline]
1061    fn styles_equivalent(&self, left: CellStyle, right: CellStyle) -> bool {
1062        left.attrs == right.attrs
1063            && self.resolve_color(left.fg) == self.resolve_color(right.fg)
1064            && self.resolve_color(left.bg) == self.resolve_color(right.bg)
1065    }
1066
1067    fn emit_foreground(&mut self, color: ResolvedColor) -> io::Result<()> {
1068        match color {
1069            ResolvedColor::Suppressed => Ok(()),
1070            ResolvedColor::Default => ansi::sgr_fg_default(&mut self.writer),
1071            ResolvedColor::Ansi16(index) => ansi::sgr_fg_16(&mut self.writer, index),
1072            ResolvedColor::Ansi256(index) => ansi::sgr_fg_256(&mut self.writer, index),
1073            ResolvedColor::TrueColor(r, g, b) => ansi::sgr_fg_rgb(&mut self.writer, r, g, b),
1074        }
1075    }
1076
1077    fn emit_background(&mut self, color: ResolvedColor) -> io::Result<()> {
1078        match color {
1079            ResolvedColor::Suppressed => Ok(()),
1080            ResolvedColor::Default => ansi::sgr_bg_default(&mut self.writer),
1081            ResolvedColor::Ansi16(index) => ansi::sgr_bg_16(&mut self.writer, index),
1082            ResolvedColor::Ansi256(index) => ansi::sgr_bg_256(&mut self.writer, index),
1083            ResolvedColor::TrueColor(r, g, b) => ansi::sgr_bg_rgb(&mut self.writer, r, g, b),
1084        }
1085    }
1086
1087    #[inline]
1088    fn dec_len_u8(value: u8) -> u32 {
1089        if value >= 100 {
1090            3
1091        } else if value >= 10 {
1092            2
1093        } else {
1094            1
1095        }
1096    }
1097
1098    #[inline]
1099    fn sgr_code_len(code: u8) -> u32 {
1100        2 + Self::dec_len_u8(code) + 1
1101    }
1102
1103    #[inline]
1104    fn sgr_flags_len(flags: StyleFlags) -> u32 {
1105        if flags.is_empty() {
1106            return 0;
1107        }
1108        let mut count = 0u32;
1109        let mut digits = 0u32;
1110        for (flag, codes) in ansi::FLAG_TABLE {
1111            if flags.contains(flag) {
1112                count += 1;
1113                digits += Self::dec_len_u8(codes.on);
1114            }
1115        }
1116        if count == 0 {
1117            return 0;
1118        }
1119        3 + digits + (count - 1)
1120    }
1121
1122    #[inline]
1123    fn sgr_flags_off_len(flags: StyleFlags) -> u32 {
1124        if flags.is_empty() {
1125            return 0;
1126        }
1127        let mut len = 0u32;
1128        for (flag, codes) in ansi::FLAG_TABLE {
1129            if flags.contains(flag) {
1130                len += Self::sgr_code_len(codes.off);
1131            }
1132        }
1133        len
1134    }
1135
1136    #[inline]
1137    fn sgr_truecolor_len(r: u8, g: u8, b: u8) -> u32 {
1138        10 + Self::dec_len_u8(r) + Self::dec_len_u8(g) + Self::dec_len_u8(b)
1139    }
1140
1141    #[inline]
1142    fn sgr_color_len(color: ResolvedColor, background: bool) -> u32 {
1143        match color {
1144            ResolvedColor::Suppressed => 0,
1145            ResolvedColor::Default => 5,
1146            ResolvedColor::Ansi16(index) if background && index >= 8 => 6,
1147            ResolvedColor::Ansi16(_) => 5,
1148            ResolvedColor::Ansi256(index) => 8 + Self::dec_len_u8(index),
1149            ResolvedColor::TrueColor(r, g, b) => Self::sgr_truecolor_len(r, g, b),
1150        }
1151    }
1152
1153    /// Emit minimal SGR delta between old and new styles.
1154    ///
1155    /// Computes which properties changed and emits only those.
1156    /// Falls back to reset+apply when that would produce fewer bytes.
1157    fn emit_style_delta(&mut self, old: CellStyle, new: CellStyle) -> io::Result<()> {
1158        let attrs_removed = old.attrs & !new.attrs;
1159        let attrs_added = new.attrs & !old.attrs;
1160        let old_fg = self.resolve_color(old.fg);
1161        let new_fg = self.resolve_color(new.fg);
1162        let old_bg = self.resolve_color(old.bg);
1163        let new_bg = self.resolve_color(new.bg);
1164        let fg_changed = old_fg != new_fg;
1165        let bg_changed = old_bg != new_bg;
1166
1167        // Hot path for VFX-style workloads: attributes are unchanged and only
1168        // colors vary. In this case, delta emission is always no worse than a
1169        // reset+reapply baseline, so skip cost estimation and flag diff logic.
1170        if old.attrs == new.attrs {
1171            if fg_changed {
1172                self.emit_foreground(new_fg)?;
1173            }
1174            if bg_changed {
1175                self.emit_background(new_bg)?;
1176            }
1177            return Ok(());
1178        }
1179
1180        let mut collateral = StyleFlags::empty();
1181        if attrs_removed.contains(StyleFlags::BOLD) && new.attrs.contains(StyleFlags::DIM) {
1182            collateral |= StyleFlags::DIM;
1183        }
1184        if attrs_removed.contains(StyleFlags::DIM) && new.attrs.contains(StyleFlags::BOLD) {
1185            collateral |= StyleFlags::BOLD;
1186        }
1187        // A flag that is both collateral (knocked out by the shared off-code
1188        // 22) and newly added is emitted once by the attrs_added pass below;
1189        // re-enabling it here too would duplicate the sequence (and bias the
1190        // estimate toward the reset+reapply fallback).
1191        let collateral_reenable = collateral & !attrs_added;
1192
1193        let mut delta_len = 0u32;
1194        delta_len += Self::sgr_flags_off_len(attrs_removed);
1195        delta_len += Self::sgr_flags_len(collateral_reenable);
1196        delta_len += Self::sgr_flags_len(attrs_added);
1197        if fg_changed {
1198            delta_len += Self::sgr_color_len(new_fg, false);
1199        }
1200        if bg_changed {
1201            delta_len += Self::sgr_color_len(new_bg, true);
1202        }
1203
1204        let mut baseline_len = 4u32;
1205        if !matches!(new_fg, ResolvedColor::Default | ResolvedColor::Suppressed) {
1206            baseline_len += Self::sgr_color_len(new_fg, false);
1207        }
1208        if !matches!(new_bg, ResolvedColor::Default | ResolvedColor::Suppressed) {
1209            baseline_len += Self::sgr_color_len(new_bg, true);
1210        }
1211        baseline_len += Self::sgr_flags_len(new.attrs);
1212
1213        if delta_len > baseline_len {
1214            return self.emit_style_full(new);
1215        }
1216
1217        // Handle attr removal: emit individual off codes
1218        if !attrs_removed.is_empty() {
1219            let collateral = ansi::sgr_flags_off(&mut self.writer, attrs_removed, new.attrs)?;
1220            // Re-enable any collaterally disabled flags — except those the
1221            // attrs_added pass below emits anyway.
1222            let reenable = collateral & !attrs_added;
1223            if !reenable.is_empty() {
1224                ansi::sgr_flags(&mut self.writer, reenable)?;
1225            }
1226        }
1227
1228        // Handle attr addition: emit on codes for newly added flags
1229        if !attrs_added.is_empty() {
1230            ansi::sgr_flags(&mut self.writer, attrs_added)?;
1231        }
1232
1233        // Handle fg color change
1234        if fg_changed {
1235            self.emit_foreground(new_fg)?;
1236        }
1237
1238        // Handle bg color change
1239        if bg_changed {
1240            self.emit_background(new_bg)?;
1241        }
1242
1243        Ok(())
1244    }
1245
1246    /// Emit hyperlink changes if the cell link differs from current.
1247    fn emit_link_changes(&mut self, cell: &Cell, links: Option<&LinkRegistry>) -> io::Result<()> {
1248        // Respect capability policy so callers running in mux contexts don't
1249        // emit OSC 8 sequences even if the raw capability flag is set.
1250        if !self.hyperlinks_enabled {
1251            if self.current_link.is_none() {
1252                return Ok(());
1253            }
1254            if self.current_link.is_some() {
1255                ansi::hyperlink_end(&mut self.writer)?;
1256            }
1257            self.current_link = None;
1258            return Ok(());
1259        }
1260
1261        let raw_link_id = cell.attrs.link_id();
1262        let new_link = if raw_link_id == CellAttrs::LINK_ID_NONE {
1263            None
1264        } else {
1265            Some(raw_link_id)
1266        };
1267
1268        // Check if link changed
1269        if self.current_link == new_link {
1270            return Ok(());
1271        }
1272
1273        // Close current link if open
1274        if self.current_link.is_some() {
1275            ansi::hyperlink_end(&mut self.writer)?;
1276        }
1277
1278        // Open new link if present and resolvable
1279        let actually_opened = if let (Some(link_id), Some(registry)) = (new_link, links)
1280            && let Some(url) = registry.get(link_id)
1281            && is_safe_hyperlink_url(url)
1282        {
1283            ansi::hyperlink_start(&mut self.writer, url)?;
1284            true
1285        } else {
1286            false
1287        };
1288
1289        // Only track as current if we actually opened it
1290        self.current_link = if actually_opened { new_link } else { None };
1291        Ok(())
1292    }
1293
1294    /// Emit cell content after width/content classification.
1295    fn emit_content(
1296        &mut self,
1297        content: PreparedContent,
1298        raw_width: usize,
1299        pool: Option<&GraphemePool>,
1300    ) -> io::Result<()> {
1301        match content {
1302            PreparedContent::Grapheme(grapheme_id) => {
1303                if let Some(pool) = pool
1304                    && let Some(text) = pool.get(grapheme_id)
1305                {
1306                    let safe = sanitize(text);
1307                    if !safe.is_empty() && display_width(safe.as_ref()) == raw_width {
1308                        return self.writer.write_all(safe.as_bytes());
1309                    }
1310                }
1311                // Fallback when sanitization strips bytes or changes display width:
1312                // emit width-1 placeholders so the terminal cursor advances by the
1313                // exact number of cells encoded in the grapheme ID.
1314                if raw_width > 0 {
1315                    for _ in 0..raw_width {
1316                        self.writer.write_all(b"?")?;
1317                    }
1318                }
1319                Ok(())
1320            }
1321            PreparedContent::Char(ch) => {
1322                if ch.is_ascii() {
1323                    // Width-0 ASCII controls are filtered earlier via the
1324                    // replacement-character path. The remaining ASCII controls
1325                    // here are width-1 (`\n`/`\r`) and must still sanitize to
1326                    // a visually neutral single cell.
1327                    let byte = if ch.is_ascii_control() {
1328                        b' '
1329                    } else {
1330                        ch as u8
1331                    };
1332                    return self.writer.write_all(&[byte]);
1333                }
1334                // Sanitize control characters that would break the grid.
1335                let safe_ch = if ch.is_control() { ' ' } else { ch };
1336                let mut buf = [0u8; 4];
1337                let encoded = safe_ch.encode_utf8(&mut buf);
1338                self.writer.write_all(encoded.as_bytes())
1339            }
1340            PreparedContent::Empty => {
1341                // Empty cell - emit space
1342                self.writer.write_all(b" ")
1343            }
1344        }
1345    }
1346
1347    /// Move cursor to the specified position.
1348    fn move_cursor_to(&mut self, x: u16, y: u16) -> io::Result<()> {
1349        // Skip if already at position
1350        if self.cursor_x == Some(x) && self.cursor_y == Some(y) {
1351            return Ok(());
1352        }
1353
1354        // Use CUP (cursor position) for absolute positioning
1355        self.cup_row(y, x)?;
1356        self.cursor_x = Some(x);
1357        self.cursor_y = Some(y);
1358        Ok(())
1359    }
1360
1361    /// Move cursor using the cheapest available operation.
1362    ///
1363    /// Compares CUP (absolute), CHA (column-only), and CUF/CUB (relative)
1364    /// to select the minimum-cost cursor movement.
1365    fn move_cursor_optimal(&mut self, x: u16, y: u16) -> io::Result<()> {
1366        // Skip if already at position
1367        if self.cursor_x == Some(x) && self.cursor_y == Some(y) {
1368            return Ok(());
1369        }
1370
1371        // Decide cheapest move
1372        let same_row = self.cursor_y == Some(y);
1373        let actual_y = y.saturating_add(self.viewport_offset_y);
1374
1375        if same_row {
1376            if let Some(cx) = self.cursor_x {
1377                if x > cx {
1378                    // Forward
1379                    let dx = x - cx;
1380                    let cuf = cost_model::cuf_cost(dx);
1381                    let cha = cost_model::cha_cost(x);
1382                    let cup = cost_model::cup_cost(actual_y, x);
1383
1384                    if cuf <= cha && cuf <= cup {
1385                        ansi::cuf(&mut self.writer, dx)?;
1386                    } else if cha <= cup {
1387                        ansi::cha(&mut self.writer, x)?;
1388                    } else {
1389                        self.cup_row(y, x)?;
1390                    }
1391                } else if x < cx {
1392                    // Backward
1393                    let dx = cx - x;
1394                    let cub = cost_model::cub_cost(dx);
1395                    let cha = cost_model::cha_cost(x);
1396                    let cup = cost_model::cup_cost(actual_y, x);
1397
1398                    if cha <= cub && cha <= cup {
1399                        ansi::cha(&mut self.writer, x)?;
1400                    } else if cub <= cup {
1401                        ansi::cub(&mut self.writer, dx)?;
1402                    } else {
1403                        self.cup_row(y, x)?;
1404                    }
1405                } else {
1406                    // Same column (should have been caught by early check, but for safety)
1407                }
1408            } else {
1409                // Unknown x, same row (unlikely but possible if we only tracked y?)
1410                // Fallback to absolute
1411                self.cup_row(y, x)?;
1412            }
1413        } else {
1414            // Different row: CUP is the only option
1415            self.cup_row(y, x)?;
1416        }
1417
1418        self.cursor_x = Some(x);
1419        self.cursor_y = Some(y);
1420        Ok(())
1421    }
1422
1423    /// Clear the entire screen.
1424    pub fn clear_screen(&mut self) -> io::Result<()> {
1425        ansi::erase_display(&mut self.writer, ansi::EraseDisplayMode::All)?;
1426        ansi::cup(&mut self.writer, 0, 0)?;
1427        self.cursor_x = Some(0);
1428        // The tracker stores viewport-relative rows; the physical home row is
1429        // only representable when the viewport offset is 0. Otherwise the next
1430        // positioning must be absolute — recording relative row 0 here would
1431        // alias physical row `viewport_offset_y` and corrupt scrollback via a
1432        // same-row CHA/CUF move.
1433        self.cursor_y = if self.viewport_offset_y == 0 {
1434            Some(0)
1435        } else {
1436            None
1437        };
1438        self.writer.flush()
1439    }
1440
1441    /// Clear a single line.
1442    pub fn clear_line(&mut self, y: u16) -> io::Result<()> {
1443        self.move_cursor_to(0, y)?;
1444        ansi::erase_line(&mut self.writer, EraseLineMode::All)?;
1445        self.writer.flush()
1446    }
1447
1448    /// Hide the cursor.
1449    pub fn hide_cursor(&mut self) -> io::Result<()> {
1450        ansi::cursor_hide(&mut self.writer)?;
1451        self.writer.flush()
1452    }
1453
1454    /// Show the cursor.
1455    pub fn show_cursor(&mut self) -> io::Result<()> {
1456        ansi::cursor_show(&mut self.writer)?;
1457        self.writer.flush()
1458    }
1459
1460    /// Position the cursor at the specified coordinates.
1461    pub fn position_cursor(&mut self, x: u16, y: u16) -> io::Result<()> {
1462        self.move_cursor_to(x, y)?;
1463        self.writer.flush()
1464    }
1465
1466    /// Reset the presenter state.
1467    ///
1468    /// Useful after resize or when terminal state is unknown.
1469    pub fn reset(&mut self) {
1470        self.current_style = None;
1471        self.current_link = None;
1472        self.cursor_x = None;
1473        self.cursor_y = None;
1474    }
1475
1476    /// Flush any buffered output.
1477    pub fn flush(&mut self) -> io::Result<()> {
1478        self.writer.flush()
1479    }
1480
1481    /// Get the inner writer (consuming the presenter).
1482    ///
1483    /// Flushes any buffered data before returning the writer.
1484    pub fn into_inner(self) -> Result<W, io::Error> {
1485        self.writer
1486            .into_inner() // CountingWriter -> BufWriter<W>
1487            .into_inner() // BufWriter<W> -> Result<W, IntoInnerError>
1488            .map_err(|e| e.into_error())
1489    }
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494    use super::*;
1495    use crate::cell::{CellAttrs, CellContent};
1496    use crate::link_registry::LinkRegistry;
1497
1498    fn test_presenter() -> Presenter<Vec<u8>> {
1499        let mut caps = TerminalCapabilities::basic();
1500        caps.color_depth = ColorDepth::TrueColor;
1501        Presenter::new(Vec::new(), caps)
1502    }
1503
1504    fn test_presenter_with_sync() -> Presenter<Vec<u8>> {
1505        let mut caps = TerminalCapabilities::basic();
1506        caps.color_depth = ColorDepth::TrueColor;
1507        caps.sync_output = true;
1508        Presenter::new(Vec::new(), caps)
1509    }
1510
1511    fn test_presenter_with_hyperlinks() -> Presenter<Vec<u8>> {
1512        let mut caps = TerminalCapabilities::basic();
1513        caps.color_depth = ColorDepth::TrueColor;
1514        caps.osc8_hyperlinks = true;
1515        Presenter::new(Vec::new(), caps)
1516    }
1517
1518    fn get_output(presenter: Presenter<Vec<u8>>) -> Vec<u8> {
1519        presenter.into_inner().unwrap()
1520    }
1521
1522    fn presenter_for_color_depth(depth: ColorDepth) -> Presenter<Vec<u8>> {
1523        let mut caps = TerminalCapabilities::basic();
1524        caps.color_depth = depth;
1525        Presenter::new(Vec::new(), caps)
1526    }
1527
1528    #[test]
1529    fn style_emission_respects_each_color_depth() {
1530        let style = CellStyle {
1531            fg: PackedRgba::rgb(255, 0, 0),
1532            bg: PackedRgba::rgb(0, 0, 255),
1533            attrs: StyleFlags::empty(),
1534        };
1535
1536        let mut truecolor = presenter_for_color_depth(ColorDepth::TrueColor);
1537        truecolor.emit_style_full(style).unwrap();
1538        assert_eq!(
1539            get_output(truecolor),
1540            b"\x1b[0m\x1b[38;2;255;0;0m\x1b[48;2;0;0;255m"
1541        );
1542
1543        let mut ansi256 = presenter_for_color_depth(ColorDepth::Ansi256);
1544        ansi256.emit_style_full(style).unwrap();
1545        assert_eq!(get_output(ansi256), b"\x1b[0m\x1b[38;5;196m\x1b[48;5;21m");
1546
1547        let mut ansi16 = presenter_for_color_depth(ColorDepth::Ansi16);
1548        ansi16.emit_style_full(style).unwrap();
1549        assert_eq!(get_output(ansi16), b"\x1b[0m\x1b[91m\x1b[44m");
1550
1551        let mut mono = presenter_for_color_depth(ColorDepth::Mono);
1552        mono.emit_style_full(style).unwrap();
1553        assert_eq!(get_output(mono), b"\x1b[0m");
1554    }
1555
1556    #[test]
1557    fn downgraded_equivalent_colors_do_not_reemit_style() {
1558        let mut presenter = presenter_for_color_depth(ColorDepth::Ansi16);
1559        let first = CellStyle {
1560            fg: PackedRgba::rgb(255, 0, 0),
1561            bg: PackedRgba::TRANSPARENT,
1562            attrs: StyleFlags::empty(),
1563        };
1564        let equivalent = CellStyle {
1565            fg: PackedRgba::rgb(254, 1, 1),
1566            ..first
1567        };
1568
1569        presenter.current_style = Some(first);
1570        presenter.emit_style_delta(first, equivalent).unwrap();
1571        assert!(get_output(presenter).is_empty());
1572    }
1573
1574    fn legacy_plan_row(
1575        row_runs: &[ChangeRun],
1576        prev_x: Option<u16>,
1577        prev_y: Option<u16>,
1578    ) -> Vec<cost_model::RowSpan> {
1579        if row_runs.is_empty() {
1580            return Vec::new();
1581        }
1582
1583        if row_runs.len() == 1 {
1584            let run = row_runs[0];
1585            return vec![cost_model::RowSpan {
1586                y: run.y,
1587                x0: run.x0,
1588                x1: run.x1,
1589            }];
1590        }
1591
1592        let row_y = row_runs[0].y;
1593        let first_x = row_runs[0].x0;
1594        let last_x = row_runs[row_runs.len() - 1].x1;
1595
1596        // Estimate sparse cost: sum of move + content for each run
1597        let mut sparse_cost: usize = 0;
1598        let mut cursor_x = prev_x;
1599        let mut cursor_y = prev_y;
1600
1601        for run in row_runs {
1602            let move_cost = cost_model::cheapest_move_cost(cursor_x, cursor_y, run.x0, run.y);
1603            let cells = (run.x1 as usize).saturating_sub(run.x0 as usize) + 1;
1604            sparse_cost += move_cost + cells;
1605            cursor_x = Some(run.x1.saturating_add(1));
1606            cursor_y = Some(row_y);
1607        }
1608
1609        // Estimate merged cost: one move + all cells from first to last
1610        let merge_move = cost_model::cheapest_move_cost(prev_x, prev_y, first_x, row_y);
1611        let total_cells = (last_x as usize).saturating_sub(first_x as usize) + 1;
1612        let changed_cells: usize = row_runs
1613            .iter()
1614            .map(|r| (r.x1 as usize).saturating_sub(r.x0 as usize) + 1)
1615            .sum();
1616        let gap_cells = total_cells.saturating_sub(changed_cells);
1617        let gap_overhead = gap_cells * 2;
1618        let merged_cost = merge_move + changed_cells + gap_overhead;
1619
1620        if merged_cost < sparse_cost {
1621            vec![cost_model::RowSpan {
1622                y: row_y,
1623                x0: first_x,
1624                x1: last_x,
1625            }]
1626        } else {
1627            row_runs
1628                .iter()
1629                .map(|run| cost_model::RowSpan {
1630                    y: run.y,
1631                    x0: run.x0,
1632                    x1: run.x1,
1633                })
1634                .collect()
1635        }
1636    }
1637
1638    fn emit_spans_for_output(buffer: &Buffer, spans: &[cost_model::RowSpan]) -> Vec<u8> {
1639        let mut presenter = test_presenter();
1640
1641        for span in spans {
1642            presenter
1643                .move_cursor_optimal(span.x0, span.y)
1644                .expect("cursor move should succeed");
1645            for x in span.x0..=span.x1 {
1646                let cell = buffer.get_unchecked(x, span.y);
1647                presenter
1648                    .emit_cell(x, cell, None, None)
1649                    .expect("emit_cell should succeed");
1650            }
1651        }
1652
1653        presenter
1654            .writer
1655            .write_all(b"\x1b[0m")
1656            .expect("reset should succeed");
1657
1658        presenter.into_inner().expect("presenter output")
1659    }
1660
1661    fn emit_spans_with_links_for_output(
1662        buffer: &Buffer,
1663        spans: &[cost_model::RowSpan],
1664        links: &LinkRegistry,
1665    ) -> Vec<u8> {
1666        let mut presenter = test_presenter_with_hyperlinks();
1667
1668        for span in spans {
1669            presenter
1670                .move_cursor_optimal(span.x0, span.y)
1671                .expect("cursor move should succeed");
1672            for x in span.x0..=span.x1 {
1673                let cell = buffer.get_unchecked(x, span.y);
1674                presenter
1675                    .emit_cell(x, cell, None, Some(links))
1676                    .expect("emit_cell should succeed");
1677            }
1678        }
1679
1680        presenter
1681            .finish_frame()
1682            .expect("frame cleanup should succeed");
1683        presenter.into_inner().expect("presenter output")
1684    }
1685
1686    #[test]
1687    fn empty_diff_produces_minimal_output() {
1688        let mut presenter = test_presenter();
1689        let buffer = Buffer::new(10, 10);
1690        let diff = BufferDiff::new();
1691
1692        presenter.present(&buffer, &diff).unwrap();
1693        let output = get_output(presenter);
1694
1695        // Without sync, fallback hides cursor first, then SGR reset, then cursor show
1696        assert!(output.starts_with(ansi::CURSOR_HIDE));
1697        assert!(output.ends_with(ansi::CURSOR_SHOW));
1698        // SGR reset is still present between the cursor brackets
1699        assert!(
1700            output.windows(b"\x1b[0m".len()).any(|w| w == b"\x1b[0m"),
1701            "SGR reset should be present"
1702        );
1703    }
1704
1705    #[test]
1706    fn sync_output_wraps_frame() {
1707        let mut presenter = test_presenter_with_sync();
1708        let mut buffer = Buffer::new(3, 1);
1709        buffer.set_raw(0, 0, Cell::from_char('X'));
1710
1711        let old = Buffer::new(3, 1);
1712        let diff = BufferDiff::compute(&old, &buffer);
1713
1714        presenter.present(&buffer, &diff).unwrap();
1715        let output = get_output(presenter);
1716
1717        assert!(
1718            output.starts_with(ansi::SYNC_BEGIN),
1719            "sync output should begin with DEC 2026 begin"
1720        );
1721        assert!(
1722            output.ends_with(ansi::SYNC_END),
1723            "sync output should end with DEC 2026 end"
1724        );
1725    }
1726
1727    #[test]
1728    fn sync_output_obeys_mux_policy() {
1729        let caps = TerminalCapabilities::builder()
1730            .sync_output(true)
1731            .in_tmux(true)
1732            .build();
1733        let mut presenter = Presenter::new(Vec::new(), caps);
1734
1735        let mut buffer = Buffer::new(2, 1);
1736        buffer.set_raw(0, 0, Cell::from_char('X'));
1737        let old = Buffer::new(2, 1);
1738        let diff = BufferDiff::compute(&old, &buffer);
1739
1740        presenter.present(&buffer, &diff).unwrap();
1741        let output = get_output(presenter);
1742
1743        assert!(
1744            !output
1745                .windows(ansi::SYNC_BEGIN.len())
1746                .any(|w| w == ansi::SYNC_BEGIN),
1747            "tmux policy should suppress sync begin"
1748        );
1749        assert!(
1750            !output
1751                .windows(ansi::SYNC_END.len())
1752                .any(|w| w == ansi::SYNC_END),
1753            "tmux policy should suppress sync end"
1754        );
1755    }
1756
1757    #[test]
1758    fn hyperlink_sequences_emitted_and_closed() {
1759        let mut presenter = test_presenter_with_hyperlinks();
1760        let mut buffer = Buffer::new(3, 1);
1761
1762        let mut registry = LinkRegistry::new();
1763        let link_id = registry.register("https://example.com");
1764        let linked = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id));
1765        buffer.set_raw(0, 0, linked);
1766
1767        let old = Buffer::new(3, 1);
1768        let diff = BufferDiff::compute(&old, &buffer);
1769
1770        presenter
1771            .present_with_pool(&buffer, &diff, None, Some(&registry))
1772            .unwrap();
1773        let output = get_output(presenter);
1774
1775        let start = b"\x1b]8;;https://example.com\x07";
1776        let end = b"\x1b]8;;\x07";
1777
1778        let start_pos = output
1779            .windows(start.len())
1780            .position(|w| w == start)
1781            .expect("hyperlink start not found");
1782        let end_pos = output
1783            .windows(end.len())
1784            .position(|w| w == end)
1785            .expect("hyperlink end not found");
1786        let char_pos = output
1787            .iter()
1788            .position(|&b| b == b'L')
1789            .expect("linked character not found");
1790
1791        assert!(start_pos < char_pos, "link start should precede text");
1792        assert!(char_pos < end_pos, "link end should follow text");
1793    }
1794
1795    #[test]
1796    fn single_cell_change() {
1797        let mut presenter = test_presenter();
1798        let mut buffer = Buffer::new(10, 10);
1799        buffer.set_raw(5, 5, Cell::from_char('X'));
1800
1801        let old = Buffer::new(10, 10);
1802        let diff = BufferDiff::compute(&old, &buffer);
1803
1804        presenter.present(&buffer, &diff).unwrap();
1805        let output = get_output(presenter);
1806
1807        // Should contain cursor position and character
1808        let output_str = String::from_utf8_lossy(&output);
1809        assert!(output_str.contains("X"));
1810        assert!(output_str.contains("\x1b[")); // Contains escape sequences
1811    }
1812
1813    #[test]
1814    fn style_tracking_avoids_redundant_sgr() {
1815        let mut presenter = test_presenter();
1816        let mut buffer = Buffer::new(10, 1);
1817
1818        // Set multiple cells with same style
1819        let fg = PackedRgba::rgb(255, 0, 0);
1820        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg));
1821        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg));
1822        buffer.set_raw(2, 0, Cell::from_char('C').with_fg(fg));
1823
1824        let old = Buffer::new(10, 1);
1825        let diff = BufferDiff::compute(&old, &buffer);
1826
1827        presenter.present(&buffer, &diff).unwrap();
1828        let output = get_output(presenter);
1829
1830        // Count SGR sequences (should be minimal due to style tracking)
1831        let output_str = String::from_utf8_lossy(&output);
1832        let sgr_count = output_str.matches("\x1b[38;2").count();
1833        // Should have exactly 1 fg color sequence (style set once, reused for ABC)
1834        assert_eq!(
1835            sgr_count, 1,
1836            "Expected 1 SGR fg sequence, got {}",
1837            sgr_count
1838        );
1839    }
1840
1841    #[test]
1842    fn reset_reapplies_style_after_clear() {
1843        let mut presenter = test_presenter();
1844        let mut buffer = Buffer::new(1, 1);
1845        let styled = Cell::from_char('A').with_fg(PackedRgba::rgb(10, 20, 30));
1846        buffer.set_raw(0, 0, styled);
1847
1848        let old = Buffer::new(1, 1);
1849        let diff = BufferDiff::compute(&old, &buffer);
1850
1851        presenter.present(&buffer, &diff).unwrap();
1852        presenter.reset();
1853        presenter.present(&buffer, &diff).unwrap();
1854
1855        let output = get_output(presenter);
1856        let output_str = String::from_utf8_lossy(&output);
1857        let sgr_count = output_str.matches("\x1b[38;2").count();
1858
1859        assert_eq!(
1860            sgr_count, 2,
1861            "Expected style to be re-applied after reset, got {sgr_count} sequences"
1862        );
1863    }
1864
1865    #[test]
1866    fn cursor_position_optimized() {
1867        let mut presenter = test_presenter();
1868        let mut buffer = Buffer::new(10, 5);
1869
1870        // Set adjacent cells (should be one run)
1871        buffer.set_raw(3, 2, Cell::from_char('A'));
1872        buffer.set_raw(4, 2, Cell::from_char('B'));
1873        buffer.set_raw(5, 2, Cell::from_char('C'));
1874
1875        let old = Buffer::new(10, 5);
1876        let diff = BufferDiff::compute(&old, &buffer);
1877
1878        presenter.present(&buffer, &diff).unwrap();
1879        let output = get_output(presenter);
1880
1881        // Should have only one CUP sequence for the run
1882        let output_str = String::from_utf8_lossy(&output);
1883        let _cup_count = output_str.matches("\x1b[").filter(|_| true).count();
1884
1885        // Content should be "ABC" somewhere in output
1886        assert!(
1887            output_str.contains("ABC")
1888                || (output_str.contains('A')
1889                    && output_str.contains('B')
1890                    && output_str.contains('C'))
1891        );
1892    }
1893
1894    #[test]
1895    fn sync_output_wrapped_when_supported() {
1896        let mut presenter = test_presenter_with_sync();
1897        let buffer = Buffer::new(10, 10);
1898        let diff = BufferDiff::new();
1899
1900        presenter.present(&buffer, &diff).unwrap();
1901        let output = get_output(presenter);
1902
1903        // Should have sync begin and end
1904        assert!(output.starts_with(ansi::SYNC_BEGIN));
1905        assert!(
1906            output
1907                .windows(ansi::SYNC_END.len())
1908                .any(|w| w == ansi::SYNC_END)
1909        );
1910    }
1911
1912    #[test]
1913    fn clear_screen_works() {
1914        let mut presenter = test_presenter();
1915        presenter.clear_screen().unwrap();
1916        let output = get_output(presenter);
1917
1918        // Should contain erase display sequence
1919        assert!(output.windows(b"\x1b[2J".len()).any(|w| w == b"\x1b[2J"));
1920    }
1921
1922    #[test]
1923    fn cursor_advance_invalidates_at_last_column() {
1924        // Reaching (or passing, for a wide cell) the presentation width parks
1925        // a real autowrap terminal in wrap-pending state at width-1; the
1926        // tracker must go unknown instead of holding a phantom column that
1927        // would skew the next same-row relative move by one.
1928        assert_eq!(
1929            Presenter::<Vec<u8>>::advance_or_invalidate(119, 1, 120),
1930            None
1931        );
1932        assert_eq!(
1933            Presenter::<Vec<u8>>::advance_or_invalidate(118, 2, 120),
1934            None
1935        );
1936        assert_eq!(
1937            Presenter::<Vec<u8>>::advance_or_invalidate(100, 2, 120),
1938            Some(102)
1939        );
1940        // Unknown presentation width (before the first present): keep advancing.
1941        assert_eq!(
1942            Presenter::<Vec<u8>>::advance_or_invalidate(119, 1, 0),
1943            Some(120)
1944        );
1945    }
1946
1947    #[test]
1948    fn move_after_end_of_row_emission_is_absolute() {
1949        let mut presenter = test_presenter();
1950        presenter.presentation_width = 120;
1951        // As after a run that ended at the last column: column unknown.
1952        presenter.cursor_x = None;
1953        presenter.cursor_y = Some(20);
1954        presenter.move_cursor_optimal(110, 20).unwrap();
1955        let output = get_output(presenter);
1956        let s = String::from_utf8_lossy(&output);
1957        // Absolute CUP (row 21, col 111), never a relative CUB from a
1958        // phantom column.
1959        assert!(s.contains("\x1b[21;111H"), "output: {s:?}");
1960        assert!(!s.ends_with('D'), "relative CUB emitted: {s:?}");
1961    }
1962
1963    #[test]
1964    fn clear_screen_with_viewport_offset_forces_absolute_next_move() {
1965        let mut presenter = test_presenter();
1966        presenter.set_viewport_offset_y(5);
1967        presenter.clear_screen().unwrap();
1968        // Physical row 0 is not representable in viewport-relative coords
1969        // when the offset is nonzero.
1970        assert_eq!(presenter.cursor_x, Some(0));
1971        assert_eq!(presenter.cursor_y, None);
1972        presenter.move_cursor_optimal(3, 0).unwrap();
1973        let output = get_output(presenter);
1974        let s = String::from_utf8_lossy(&output);
1975        // Viewport row 0 = physical row 5 -> absolute CUP row 6, col 4; a
1976        // same-row CHA/CUF here would have written onto physical row 0.
1977        assert!(s.contains("\x1b[6;4H"), "output: {s:?}");
1978    }
1979
1980    #[test]
1981    fn cursor_visibility() {
1982        let mut presenter = test_presenter();
1983
1984        presenter.hide_cursor().unwrap();
1985        presenter.show_cursor().unwrap();
1986
1987        let output = get_output(presenter);
1988        let output_str = String::from_utf8_lossy(&output);
1989
1990        assert!(output_str.contains("\x1b[?25l")); // Hide
1991        assert!(output_str.contains("\x1b[?25h")); // Show
1992    }
1993
1994    #[test]
1995    fn reset_clears_state() {
1996        let mut presenter = test_presenter();
1997        presenter.cursor_x = Some(50);
1998        presenter.cursor_y = Some(20);
1999        presenter.current_style = Some(CellStyle::default());
2000
2001        presenter.reset();
2002
2003        assert!(presenter.cursor_x.is_none());
2004        assert!(presenter.cursor_y.is_none());
2005        assert!(presenter.current_style.is_none());
2006    }
2007
2008    #[test]
2009    fn position_cursor() {
2010        let mut presenter = test_presenter();
2011        presenter.position_cursor(10, 5).unwrap();
2012
2013        let output = get_output(presenter);
2014        // CUP is 1-indexed: row 6, col 11
2015        assert!(
2016            output
2017                .windows(b"\x1b[6;11H".len())
2018                .any(|w| w == b"\x1b[6;11H")
2019        );
2020    }
2021
2022    #[test]
2023    fn skip_cursor_move_when_already_at_position() {
2024        let mut presenter = test_presenter();
2025        presenter.cursor_x = Some(5);
2026        presenter.cursor_y = Some(3);
2027
2028        // Move to same position
2029        presenter.move_cursor_to(5, 3).unwrap();
2030
2031        // Should produce no output
2032        let output = get_output(presenter);
2033        assert!(output.is_empty());
2034    }
2035
2036    #[test]
2037    fn continuation_cells_skipped() {
2038        let mut presenter = test_presenter();
2039        let mut buffer = Buffer::new(10, 1);
2040
2041        // Set a wide character
2042        buffer.set_raw(0, 0, Cell::from_char('中'));
2043        // The next cell would be a continuation - simulate it
2044        buffer.set_raw(1, 0, Cell::CONTINUATION);
2045
2046        // Create a diff that includes both cells
2047        let old = Buffer::new(10, 1);
2048        let diff = BufferDiff::compute(&old, &buffer);
2049
2050        presenter.present(&buffer, &diff).unwrap();
2051        let output = get_output(presenter);
2052
2053        // Should contain the wide character
2054        let output_str = String::from_utf8_lossy(&output);
2055        assert!(output_str.contains('中'));
2056    }
2057
2058    #[test]
2059    fn continuation_at_run_start_clears_orphan_tail() {
2060        let mut presenter = test_presenter();
2061        let mut old = Buffer::new(3, 1);
2062        let mut new = Buffer::new(3, 1);
2063
2064        // Construct an inconsistent old/new pair that forces a diff which begins at a
2065        // continuation cell. This simulates starting emission mid-wide-character.
2066        //
2067        // In this case, the presenter should clear the orphan continuation cell so
2068        // stale terminal content cannot leak through.
2069        old.set_raw(0, 0, Cell::from_char('中'));
2070        new.set_raw(0, 0, Cell::from_char('中'));
2071        old.set_raw(1, 0, Cell::from_char('X'));
2072        new.set_raw(1, 0, Cell::CONTINUATION);
2073
2074        let diff = BufferDiff::compute(&old, &new);
2075        assert_eq!(diff.changes(), &[(1u16, 0u16)]);
2076
2077        presenter.present(&new, &diff).unwrap();
2078        let output = get_output(presenter);
2079
2080        assert!(
2081            output.contains(&b' '),
2082            "orphan continuation should be cleared with a space"
2083        );
2084    }
2085
2086    #[test]
2087    fn continuation_cleanup_resets_style_and_closes_link_before_space() {
2088        let mut presenter = test_presenter_with_hyperlinks();
2089        let mut links = LinkRegistry::new();
2090        let link_id = links.register("https://example.com");
2091
2092        let styled = Cell::from_char('X')
2093            .with_fg(PackedRgba::rgb(255, 0, 0))
2094            .with_bg(PackedRgba::rgb(0, 0, 255))
2095            .with_attrs(CellAttrs::new(StyleFlags::UNDERLINE, link_id));
2096        presenter.current_style = Some(CellStyle::from_cell(&styled));
2097        presenter.current_link = Some(link_id);
2098        presenter.cursor_x = Some(0);
2099        presenter.cursor_y = Some(0);
2100
2101        presenter
2102            .emit_cell(0, &Cell::CONTINUATION, None, Some(&links))
2103            .unwrap();
2104        let output = presenter.into_inner().unwrap();
2105
2106        let reset = b"\x1b[0m";
2107        let close = b"\x1b]8;;\x07";
2108        let reset_pos = output
2109            .windows(reset.len())
2110            .position(|window| window == reset)
2111            .expect("continuation cleanup should reset SGR state");
2112        let close_pos = output
2113            .windows(close.len())
2114            .position(|window| window == close)
2115            .expect("continuation cleanup should close OSC 8");
2116        let space_pos = output
2117            .iter()
2118            .position(|&byte| byte == b' ')
2119            .expect("continuation cleanup should emit a space");
2120
2121        assert!(
2122            reset_pos < space_pos,
2123            "cleanup reset must precede the blank"
2124        );
2125        assert!(
2126            close_pos < space_pos,
2127            "cleanup link close must precede the blank"
2128        );
2129    }
2130
2131    #[test]
2132    fn wide_char_missing_continuation_causes_drift() {
2133        let mut presenter = test_presenter();
2134        let mut buffer = Buffer::new(10, 1);
2135
2136        // Bug scenario: User sets wide char but forgets continuation
2137        buffer.set_raw(0, 0, Cell::from_char('中'));
2138        // (1,0) remains empty (space), instead of CONTINUATION
2139
2140        let old = Buffer::new(10, 1);
2141        let diff = BufferDiff::compute(&old, &buffer);
2142
2143        presenter.present(&buffer, &diff).unwrap();
2144        let output = get_output(presenter);
2145
2146        // Expected behavior with fix:
2147        // 1. Emit '中' at 0. Cursor -> 2.
2148        // 2. Loop visits 1. Cell is ' '.
2149        // 3. Drift check sees x=1, cx=2. Mismatch!
2150        // 4. Force move to 1. Emits CUP or CHA (CHA is cheaper: \x1b[2G).
2151        // 5. Emit ' '. Cursor -> 2.
2152
2153        // Without fix, it would just emit ' ' at 2.
2154
2155        let output_str = String::from_utf8_lossy(&output);
2156
2157        // Assert we see the wide char
2158        assert!(output_str.contains('中'));
2159
2160        // Assert we see a back-step or positioning sequence.
2161        // CHA 2 is "\x1b[2G". CUB 1 is "\x1b[D".
2162        // The cost model might choose CUB 1 (3 bytes) vs CHA 2 (4 bytes).
2163        // So check for either.
2164
2165        let has_correction = output_str.contains("\x1b[D")
2166            || output_str.contains("\x1b[2G")
2167            || output_str.contains("\x1b[1;2H");
2168
2169        assert!(
2170            has_correction,
2171            "Presenter should correct cursor drift when wide char tail is missing. Output: {:?}",
2172            output_str
2173        );
2174    }
2175
2176    #[test]
2177    fn hyperlink_emitted_with_registry() {
2178        let mut presenter = test_presenter_with_hyperlinks();
2179        let mut buffer = Buffer::new(10, 1);
2180        let mut links = LinkRegistry::new();
2181
2182        let link_id = links.register("https://example.com");
2183        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id));
2184        buffer.set_raw(0, 0, cell);
2185
2186        let old = Buffer::new(10, 1);
2187        let diff = BufferDiff::compute(&old, &buffer);
2188
2189        presenter
2190            .present_with_pool(&buffer, &diff, None, Some(&links))
2191            .unwrap();
2192        let output = get_output(presenter);
2193        let output_str = String::from_utf8_lossy(&output);
2194
2195        // OSC 8 open with URL
2196        assert!(
2197            output_str.contains("\x1b]8;;https://example.com\x07"),
2198            "Expected OSC 8 open, got: {:?}",
2199            output_str
2200        );
2201        // OSC 8 close (empty URL)
2202        assert!(
2203            output_str.contains("\x1b]8;;\x07"),
2204            "Expected OSC 8 close, got: {:?}",
2205            output_str
2206        );
2207    }
2208
2209    #[test]
2210    fn hyperlink_not_emitted_without_registry() {
2211        let mut presenter = test_presenter_with_hyperlinks();
2212        let mut buffer = Buffer::new(10, 1);
2213
2214        // Set a link ID without providing a registry
2215        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), 1));
2216        buffer.set_raw(0, 0, cell);
2217
2218        let old = Buffer::new(10, 1);
2219        let diff = BufferDiff::compute(&old, &buffer);
2220
2221        // Present without link registry
2222        presenter.present(&buffer, &diff).unwrap();
2223        let output = get_output(presenter);
2224        let output_str = String::from_utf8_lossy(&output);
2225
2226        // No OSC 8 sequences should appear
2227        assert!(
2228            !output_str.contains("\x1b]8;"),
2229            "OSC 8 should not appear without registry, got: {:?}",
2230            output_str
2231        );
2232    }
2233
2234    #[test]
2235    fn hyperlink_not_emitted_for_unknown_id() {
2236        let mut presenter = test_presenter_with_hyperlinks();
2237        let mut buffer = Buffer::new(10, 1);
2238        let links = LinkRegistry::new();
2239
2240        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), 42));
2241        buffer.set_raw(0, 0, cell);
2242
2243        let old = Buffer::new(10, 1);
2244        let diff = BufferDiff::compute(&old, &buffer);
2245
2246        presenter
2247            .present_with_pool(&buffer, &diff, None, Some(&links))
2248            .unwrap();
2249        let output = get_output(presenter);
2250        let output_str = String::from_utf8_lossy(&output);
2251
2252        assert!(
2253            !output_str.contains("\x1b]8;"),
2254            "OSC 8 should not appear for unknown link IDs, got: {:?}",
2255            output_str
2256        );
2257        assert!(output_str.contains('L'));
2258    }
2259
2260    #[test]
2261    fn hyperlink_closed_at_frame_end() {
2262        let mut presenter = test_presenter_with_hyperlinks();
2263        let mut buffer = Buffer::new(10, 1);
2264        let mut links = LinkRegistry::new();
2265
2266        let link_id = links.register("https://example.com");
2267        // Set all cells with the same link
2268        for x in 0..5 {
2269            buffer.set_raw(
2270                x,
2271                0,
2272                Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2273            );
2274        }
2275
2276        let old = Buffer::new(10, 1);
2277        let diff = BufferDiff::compute(&old, &buffer);
2278
2279        presenter
2280            .present_with_pool(&buffer, &diff, None, Some(&links))
2281            .unwrap();
2282        let output = get_output(presenter);
2283
2284        // The close sequence should appear (frame end cleanup)
2285        let close_seq = b"\x1b]8;;\x07";
2286        assert!(
2287            output.windows(close_seq.len()).any(|w| w == close_seq),
2288            "Link must be closed at frame end"
2289        );
2290    }
2291
2292    #[test]
2293    fn hyperlink_transitions_between_links() {
2294        let mut presenter = test_presenter_with_hyperlinks();
2295        let mut buffer = Buffer::new(10, 1);
2296        let mut links = LinkRegistry::new();
2297
2298        let link_a = links.register("https://a.com");
2299        let link_b = links.register("https://b.com");
2300
2301        buffer.set_raw(
2302            0,
2303            0,
2304            Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_a)),
2305        );
2306        buffer.set_raw(
2307            1,
2308            0,
2309            Cell::from_char('B').with_attrs(CellAttrs::new(StyleFlags::empty(), link_b)),
2310        );
2311        buffer.set_raw(2, 0, Cell::from_char('C')); // no link
2312
2313        let old = Buffer::new(10, 1);
2314        let diff = BufferDiff::compute(&old, &buffer);
2315
2316        presenter
2317            .present_with_pool(&buffer, &diff, None, Some(&links))
2318            .unwrap();
2319        let output = get_output(presenter);
2320        let output_str = String::from_utf8_lossy(&output);
2321
2322        // Both links should appear
2323        assert!(output_str.contains("https://a.com"));
2324        assert!(output_str.contains("https://b.com"));
2325
2326        // Close sequence must appear at least once (transition or frame end)
2327        let close_count = output_str.matches("\x1b]8;;\x07").count();
2328        assert!(
2329            close_count >= 2,
2330            "Expected at least 2 link close sequences (transition + frame end), got {}",
2331            close_count
2332        );
2333    }
2334
2335    #[test]
2336    fn hyperlink_obeys_mux_policy_even_when_capability_flag_set() {
2337        let caps = TerminalCapabilities::builder()
2338            .osc8_hyperlinks(true)
2339            .in_tmux(true)
2340            .build();
2341        let mut presenter = Presenter::new(Vec::new(), caps);
2342        let mut buffer = Buffer::new(3, 1);
2343        let mut links = LinkRegistry::new();
2344        let link_id = links.register("https://example.com");
2345        buffer.set_raw(
2346            0,
2347            0,
2348            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2349        );
2350
2351        let old = Buffer::new(3, 1);
2352        let diff = BufferDiff::compute(&old, &buffer);
2353        presenter
2354            .present_with_pool(&buffer, &diff, None, Some(&links))
2355            .unwrap();
2356
2357        let output = get_output(presenter);
2358        let output_str = String::from_utf8_lossy(&output);
2359        assert!(
2360            !output_str.contains("\x1b]8;"),
2361            "tmux policy should suppress OSC 8 sequences"
2362        );
2363        assert!(output_str.contains('L'));
2364    }
2365
2366    #[test]
2367    fn hyperlink_disabled_policy_noops_when_no_link_is_open() {
2368        let mut presenter = test_presenter();
2369        presenter
2370            .emit_link_changes(&Cell::from_char('X'), None)
2371            .unwrap();
2372        assert!(presenter.into_inner().unwrap().is_empty());
2373    }
2374
2375    #[test]
2376    fn hyperlink_disabled_policy_still_closes_stale_open_link() {
2377        let mut presenter = test_presenter();
2378        presenter.current_link = Some(7);
2379        presenter
2380            .emit_link_changes(&Cell::from_char('X'), None)
2381            .unwrap();
2382        assert_eq!(presenter.into_inner().unwrap(), b"\x1b]8;;\x07");
2383    }
2384
2385    #[test]
2386    fn hyperlink_unsafe_url_not_emitted() {
2387        let mut presenter = test_presenter_with_hyperlinks();
2388        let mut buffer = Buffer::new(3, 1);
2389        let mut links = LinkRegistry::new();
2390        let link_id = links.register("https://example.com/\x1b[?2026h");
2391        buffer.set_raw(
2392            0,
2393            0,
2394            Cell::from_char('X').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2395        );
2396
2397        let old = Buffer::new(3, 1);
2398        let diff = BufferDiff::compute(&old, &buffer);
2399        presenter
2400            .present_with_pool(&buffer, &diff, None, Some(&links))
2401            .unwrap();
2402
2403        let output = get_output(presenter);
2404        let output_str = String::from_utf8_lossy(&output);
2405        assert!(
2406            !output_str.contains("\x1b]8;;https://example.com/"),
2407            "unsafe hyperlink URL should be suppressed"
2408        );
2409        assert!(
2410            !output_str.contains("\x1b[?2026h"),
2411            "control payload must never be emitted via OSC 8"
2412        );
2413        assert!(output_str.contains('X'));
2414    }
2415
2416    #[test]
2417    fn hyperlink_overlong_url_not_emitted() {
2418        let mut presenter = test_presenter_with_hyperlinks();
2419        let mut buffer = Buffer::new(3, 1);
2420        let mut links = LinkRegistry::new();
2421        let long_url = format!(
2422            "https://example.com/{}",
2423            "a".repeat(MAX_SAFE_HYPERLINK_URL_BYTES + 1)
2424        );
2425        let link_id = links.register(&long_url);
2426        buffer.set_raw(
2427            0,
2428            0,
2429            Cell::from_char('Y').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2430        );
2431
2432        let old = Buffer::new(3, 1);
2433        let diff = BufferDiff::compute(&old, &buffer);
2434        presenter
2435            .present_with_pool(&buffer, &diff, None, Some(&links))
2436            .unwrap();
2437
2438        let output = get_output(presenter);
2439        let output_str = String::from_utf8_lossy(&output);
2440        assert!(
2441            !output_str.contains("\x1b]8;;https://example.com/"),
2442            "overlong hyperlink URL should be suppressed"
2443        );
2444        assert!(output_str.contains('Y'));
2445    }
2446
2447    // =========================================================================
2448    // Single-write-per-frame behavior tests
2449    // =========================================================================
2450
2451    #[test]
2452    fn sync_output_not_wrapped_when_unsupported() {
2453        // When sync_output capability is false, sync sequences should NOT appear
2454        let mut presenter = test_presenter(); // basic caps, sync_output = false
2455        let buffer = Buffer::new(10, 10);
2456        let diff = BufferDiff::new();
2457
2458        presenter.present(&buffer, &diff).unwrap();
2459        let output = get_output(presenter);
2460
2461        // Should NOT contain sync sequences
2462        assert!(
2463            !output
2464                .windows(ansi::SYNC_BEGIN.len())
2465                .any(|w| w == ansi::SYNC_BEGIN),
2466            "Sync begin should not appear when sync_output is disabled"
2467        );
2468        assert!(
2469            !output
2470                .windows(ansi::SYNC_END.len())
2471                .any(|w| w == ansi::SYNC_END),
2472            "Sync end should not appear when sync_output is disabled"
2473        );
2474
2475        // Instead, cursor-hide fallback should be used
2476        assert!(
2477            output.starts_with(ansi::CURSOR_HIDE),
2478            "Fallback should start with cursor hide"
2479        );
2480        assert!(
2481            output.ends_with(ansi::CURSOR_SHOW),
2482            "Fallback should end with cursor show"
2483        );
2484    }
2485
2486    #[test]
2487    fn present_flushes_buffered_output() {
2488        // Verify that present() flushes all buffered output by checking
2489        // that the output contains expected content after present()
2490        let mut presenter = test_presenter();
2491        let mut buffer = Buffer::new(5, 1);
2492        buffer.set_raw(0, 0, Cell::from_char('T'));
2493        buffer.set_raw(1, 0, Cell::from_char('E'));
2494        buffer.set_raw(2, 0, Cell::from_char('S'));
2495        buffer.set_raw(3, 0, Cell::from_char('T'));
2496
2497        let old = Buffer::new(5, 1);
2498        let diff = BufferDiff::compute(&old, &buffer);
2499
2500        presenter.present(&buffer, &diff).unwrap();
2501        let output = get_output(presenter);
2502        let output_str = String::from_utf8_lossy(&output);
2503
2504        // All characters should be present in output (flushed)
2505        assert!(
2506            output_str.contains("TEST"),
2507            "Expected 'TEST' in flushed output"
2508        );
2509    }
2510
2511    #[test]
2512    fn present_stats_reports_cells_and_bytes() {
2513        let mut presenter = test_presenter();
2514        let mut buffer = Buffer::new(10, 1);
2515
2516        // Set 5 cells
2517        for i in 0..5 {
2518            buffer.set_raw(i, 0, Cell::from_char('X'));
2519        }
2520
2521        let old = Buffer::new(10, 1);
2522        let diff = BufferDiff::compute(&old, &buffer);
2523
2524        let stats = presenter.present(&buffer, &diff).unwrap();
2525
2526        // Stats should reflect the changes
2527        assert_eq!(stats.cells_changed, 5, "Expected 5 cells changed");
2528        assert!(stats.bytes_emitted > 0, "Expected some bytes written");
2529        assert!(stats.run_count >= 1, "Expected at least 1 run");
2530    }
2531
2532    // =========================================================================
2533    // Cursor tracking tests
2534    // =========================================================================
2535
2536    #[test]
2537    fn cursor_tracking_after_wide_char() {
2538        let mut presenter = test_presenter();
2539        presenter.cursor_x = Some(0);
2540        presenter.cursor_y = Some(0);
2541
2542        let mut buffer = Buffer::new(10, 1);
2543        // Wide char at x=0 should advance cursor by 2
2544        buffer.set_raw(0, 0, Cell::from_char('中'));
2545        buffer.set_raw(1, 0, Cell::CONTINUATION);
2546        // Narrow char at x=2
2547        buffer.set_raw(2, 0, Cell::from_char('A'));
2548
2549        let old = Buffer::new(10, 1);
2550        let diff = BufferDiff::compute(&old, &buffer);
2551
2552        presenter.present(&buffer, &diff).unwrap();
2553
2554        // After presenting, cursor should be at x=3 (0 + 2 for wide + 1 for 'A')
2555        // Note: cursor_x gets reset during present(), but we can verify output order
2556        let output = get_output(presenter);
2557        let output_str = String::from_utf8_lossy(&output);
2558
2559        // Both characters should appear
2560        assert!(output_str.contains('中'));
2561        assert!(output_str.contains('A'));
2562    }
2563
2564    #[test]
2565    fn cursor_position_after_multiple_runs() {
2566        let mut presenter = test_presenter();
2567        let mut buffer = Buffer::new(20, 3);
2568
2569        // Create two separate runs on different rows
2570        buffer.set_raw(0, 0, Cell::from_char('A'));
2571        buffer.set_raw(1, 0, Cell::from_char('B'));
2572        buffer.set_raw(5, 2, Cell::from_char('X'));
2573        buffer.set_raw(6, 2, Cell::from_char('Y'));
2574
2575        let old = Buffer::new(20, 3);
2576        let diff = BufferDiff::compute(&old, &buffer);
2577
2578        presenter.present(&buffer, &diff).unwrap();
2579        let output = get_output(presenter);
2580        let output_str = String::from_utf8_lossy(&output);
2581
2582        // All characters should be present
2583        assert!(output_str.contains('A'));
2584        assert!(output_str.contains('B'));
2585        assert!(output_str.contains('X'));
2586        assert!(output_str.contains('Y'));
2587
2588        // Should have multiple CUP sequences (one per run)
2589        let cup_count = output_str.matches("\x1b[").count();
2590        assert!(
2591            cup_count >= 2,
2592            "Expected at least 2 escape sequences for multiple runs"
2593        );
2594    }
2595
2596    // =========================================================================
2597    // Style tracking tests
2598    // =========================================================================
2599
2600    #[test]
2601    fn style_with_all_flags() {
2602        let mut presenter = test_presenter();
2603        let mut buffer = Buffer::new(5, 1);
2604
2605        // Create a cell with all style flags
2606        let all_flags = StyleFlags::BOLD
2607            | StyleFlags::DIM
2608            | StyleFlags::ITALIC
2609            | StyleFlags::UNDERLINE
2610            | StyleFlags::BLINK
2611            | StyleFlags::REVERSE
2612            | StyleFlags::STRIKETHROUGH;
2613
2614        let cell = Cell::from_char('X').with_attrs(CellAttrs::new(all_flags, 0));
2615        buffer.set_raw(0, 0, cell);
2616
2617        let old = Buffer::new(5, 1);
2618        let diff = BufferDiff::compute(&old, &buffer);
2619
2620        presenter.present(&buffer, &diff).unwrap();
2621        let output = get_output(presenter);
2622        let output_str = String::from_utf8_lossy(&output);
2623
2624        // Should contain the character and SGR sequences
2625        assert!(output_str.contains('X'));
2626        // Should have SGR with multiple attributes (1;2;3;4;5;7;9m pattern)
2627        assert!(output_str.contains("\x1b["), "Expected SGR sequences");
2628    }
2629
2630    #[test]
2631    fn style_transitions_between_different_colors() {
2632        let mut presenter = test_presenter();
2633        let mut buffer = Buffer::new(3, 1);
2634
2635        // Three cells with different foreground colors
2636        buffer.set_raw(
2637            0,
2638            0,
2639            Cell::from_char('R').with_fg(PackedRgba::rgb(255, 0, 0)),
2640        );
2641        buffer.set_raw(
2642            1,
2643            0,
2644            Cell::from_char('G').with_fg(PackedRgba::rgb(0, 255, 0)),
2645        );
2646        buffer.set_raw(
2647            2,
2648            0,
2649            Cell::from_char('B').with_fg(PackedRgba::rgb(0, 0, 255)),
2650        );
2651
2652        let old = Buffer::new(3, 1);
2653        let diff = BufferDiff::compute(&old, &buffer);
2654
2655        presenter.present(&buffer, &diff).unwrap();
2656        let output = get_output(presenter);
2657        let output_str = String::from_utf8_lossy(&output);
2658
2659        // All colors should appear in the output
2660        assert!(output_str.contains("38;2;255;0;0"), "Expected red fg");
2661        assert!(output_str.contains("38;2;0;255;0"), "Expected green fg");
2662        assert!(output_str.contains("38;2;0;0;255"), "Expected blue fg");
2663    }
2664
2665    // =========================================================================
2666    // Link tracking tests
2667    // =========================================================================
2668
2669    #[test]
2670    fn link_at_buffer_boundaries() {
2671        let mut presenter = test_presenter_with_hyperlinks();
2672        let mut buffer = Buffer::new(5, 1);
2673        let mut links = LinkRegistry::new();
2674
2675        let link_id = links.register("https://boundary.test");
2676
2677        // Link at first cell
2678        buffer.set_raw(
2679            0,
2680            0,
2681            Cell::from_char('F').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2682        );
2683        // Link at last cell
2684        buffer.set_raw(
2685            4,
2686            0,
2687            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2688        );
2689
2690        let old = Buffer::new(5, 1);
2691        let diff = BufferDiff::compute(&old, &buffer);
2692
2693        presenter
2694            .present_with_pool(&buffer, &diff, None, Some(&links))
2695            .unwrap();
2696        let output = get_output(presenter);
2697        let output_str = String::from_utf8_lossy(&output);
2698
2699        // Link URL should appear
2700        assert!(output_str.contains("https://boundary.test"));
2701        // Characters should appear
2702        assert!(output_str.contains('F'));
2703        assert!(output_str.contains('L'));
2704    }
2705
2706    #[test]
2707    fn link_state_cleared_after_reset() {
2708        let mut presenter = test_presenter();
2709        let mut links = LinkRegistry::new();
2710        let link_id = links.register("https://example.com");
2711
2712        // Simulate having an open link
2713        presenter.current_link = Some(link_id);
2714        presenter.current_style = Some(CellStyle::default());
2715        presenter.cursor_x = Some(5);
2716        presenter.cursor_y = Some(3);
2717
2718        presenter.reset();
2719
2720        // All state should be cleared
2721        assert!(
2722            presenter.current_link.is_none(),
2723            "current_link should be None after reset"
2724        );
2725        assert!(
2726            presenter.current_style.is_none(),
2727            "current_style should be None after reset"
2728        );
2729        assert!(
2730            presenter.cursor_x.is_none(),
2731            "cursor_x should be None after reset"
2732        );
2733        assert!(
2734            presenter.cursor_y.is_none(),
2735            "cursor_y should be None after reset"
2736        );
2737    }
2738
2739    #[test]
2740    fn link_transitions_linked_unlinked_linked() {
2741        let mut presenter = test_presenter_with_hyperlinks();
2742        let mut buffer = Buffer::new(5, 1);
2743        let mut links = LinkRegistry::new();
2744
2745        let link_id = links.register("https://toggle.test");
2746
2747        // Linked -> Unlinked -> Linked pattern
2748        buffer.set_raw(
2749            0,
2750            0,
2751            Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2752        );
2753        buffer.set_raw(1, 0, Cell::from_char('B')); // no link
2754        buffer.set_raw(
2755            2,
2756            0,
2757            Cell::from_char('C').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
2758        );
2759
2760        let old = Buffer::new(5, 1);
2761        let diff = BufferDiff::compute(&old, &buffer);
2762
2763        presenter
2764            .present_with_pool(&buffer, &diff, None, Some(&links))
2765            .unwrap();
2766        let output = get_output(presenter);
2767        let output_str = String::from_utf8_lossy(&output);
2768
2769        // Link URL should appear at least twice (once for A, once for C)
2770        let url_count = output_str.matches("https://toggle.test").count();
2771        assert!(
2772            url_count >= 2,
2773            "Expected link to open at least twice, got {} occurrences",
2774            url_count
2775        );
2776
2777        // Close sequence should appear (after A, and at frame end)
2778        let close_count = output_str.matches("\x1b]8;;\x07").count();
2779        assert!(
2780            close_count >= 2,
2781            "Expected at least 2 link closes, got {}",
2782            close_count
2783        );
2784    }
2785
2786    // =========================================================================
2787    // Multiple frame tests
2788    // =========================================================================
2789
2790    #[test]
2791    fn multiple_presents_maintain_correct_state() {
2792        let mut presenter = test_presenter();
2793        let mut buffer = Buffer::new(10, 1);
2794
2795        // First frame
2796        buffer.set_raw(0, 0, Cell::from_char('1'));
2797        let old = Buffer::new(10, 1);
2798        let diff = BufferDiff::compute(&old, &buffer);
2799        presenter.present(&buffer, &diff).unwrap();
2800
2801        // Second frame - change a different cell
2802        let prev = buffer.clone();
2803        buffer.set_raw(1, 0, Cell::from_char('2'));
2804        let diff = BufferDiff::compute(&prev, &buffer);
2805        presenter.present(&buffer, &diff).unwrap();
2806
2807        // Third frame - change another cell
2808        let prev = buffer.clone();
2809        buffer.set_raw(2, 0, Cell::from_char('3'));
2810        let diff = BufferDiff::compute(&prev, &buffer);
2811        presenter.present(&buffer, &diff).unwrap();
2812
2813        let output = get_output(presenter);
2814        let output_str = String::from_utf8_lossy(&output);
2815
2816        // All numbers should appear in final output
2817        assert!(output_str.contains('1'));
2818        assert!(output_str.contains('2'));
2819        assert!(output_str.contains('3'));
2820    }
2821
2822    // =========================================================================
2823    // SGR Delta Engine tests (bd-4kq0.2.1)
2824    // =========================================================================
2825
2826    #[test]
2827    fn sgr_delta_fg_only_change_no_reset() {
2828        // When only fg changes, delta should NOT emit reset
2829        let mut presenter = test_presenter();
2830        let mut buffer = Buffer::new(3, 1);
2831
2832        let fg1 = PackedRgba::rgb(255, 0, 0);
2833        let fg2 = PackedRgba::rgb(0, 255, 0);
2834        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg1));
2835        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg2));
2836
2837        let old = Buffer::new(3, 1);
2838        let diff = BufferDiff::compute(&old, &buffer);
2839
2840        presenter.present(&buffer, &diff).unwrap();
2841        let output = get_output(presenter);
2842        let output_str = String::from_utf8_lossy(&output);
2843
2844        // Count SGR resets - the first cell needs a reset (from None state),
2845        // but the second cell should use delta (no reset)
2846        let reset_count = output_str.matches("\x1b[0m").count();
2847        // One reset at start (for first cell from unknown state) + one at frame end
2848        assert_eq!(
2849            reset_count, 2,
2850            "Expected 2 resets (initial + frame end), got {} in: {:?}",
2851            reset_count, output_str
2852        );
2853    }
2854
2855    #[test]
2856    fn sgr_delta_bg_only_change_no_reset() {
2857        let mut presenter = test_presenter();
2858        let mut buffer = Buffer::new(3, 1);
2859
2860        let bg1 = PackedRgba::rgb(0, 0, 255);
2861        let bg2 = PackedRgba::rgb(255, 255, 0);
2862        buffer.set_raw(0, 0, Cell::from_char('A').with_bg(bg1));
2863        buffer.set_raw(1, 0, Cell::from_char('B').with_bg(bg2));
2864
2865        let old = Buffer::new(3, 1);
2866        let diff = BufferDiff::compute(&old, &buffer);
2867
2868        presenter.present(&buffer, &diff).unwrap();
2869        let output = get_output(presenter);
2870        let output_str = String::from_utf8_lossy(&output);
2871
2872        // Only 2 resets: initial cell + frame end
2873        let reset_count = output_str.matches("\x1b[0m").count();
2874        assert_eq!(
2875            reset_count, 2,
2876            "Expected 2 resets, got {} in: {:?}",
2877            reset_count, output_str
2878        );
2879    }
2880
2881    #[test]
2882    fn sgr_delta_attr_addition_no_reset() {
2883        let mut presenter = test_presenter();
2884        let mut buffer = Buffer::new(3, 1);
2885
2886        // First cell: bold. Second cell: bold + italic
2887        let attrs1 = CellAttrs::new(StyleFlags::BOLD, 0);
2888        let attrs2 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 0);
2889        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
2890        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));
2891
2892        let old = Buffer::new(3, 1);
2893        let diff = BufferDiff::compute(&old, &buffer);
2894
2895        presenter.present(&buffer, &diff).unwrap();
2896        let output = get_output(presenter);
2897        let output_str = String::from_utf8_lossy(&output);
2898
2899        // Second cell should add italic (code 3) without reset
2900        let reset_count = output_str.matches("\x1b[0m").count();
2901        assert_eq!(
2902            reset_count, 2,
2903            "Expected 2 resets, got {} in: {:?}",
2904            reset_count, output_str
2905        );
2906        // Should contain italic-on code for the delta
2907        assert!(
2908            output_str.contains("\x1b[3m"),
2909            "Expected italic-on sequence in: {:?}",
2910            output_str
2911        );
2912    }
2913
2914    #[test]
2915    fn sgr_delta_attr_removal_uses_off_code() {
2916        let mut presenter = test_presenter();
2917        let mut buffer = Buffer::new(3, 1);
2918
2919        // First cell: bold+italic. Second cell: bold only
2920        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 0);
2921        let attrs2 = CellAttrs::new(StyleFlags::BOLD, 0);
2922        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
2923        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));
2924
2925        let old = Buffer::new(3, 1);
2926        let diff = BufferDiff::compute(&old, &buffer);
2927
2928        presenter.present(&buffer, &diff).unwrap();
2929        let output = get_output(presenter);
2930        let output_str = String::from_utf8_lossy(&output);
2931
2932        // Should contain italic-off code (23) for delta
2933        assert!(
2934            output_str.contains("\x1b[23m"),
2935            "Expected italic-off sequence in: {:?}",
2936            output_str
2937        );
2938        // Only 2 resets (initial + frame end), not 3
2939        let reset_count = output_str.matches("\x1b[0m").count();
2940        assert_eq!(
2941            reset_count, 2,
2942            "Expected 2 resets, got {} in: {:?}",
2943            reset_count, output_str
2944        );
2945    }
2946
2947    #[test]
2948    fn sgr_delta_bold_dim_collateral_re_enables() {
2949        // Bold off (code 22) also disables Dim. If Dim should remain,
2950        // the delta engine must re-enable it.
2951        let mut presenter = test_presenter();
2952        let mut buffer = Buffer::new(3, 1);
2953
2954        // First cell: Bold + Dim. Second cell: Dim only
2955        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::DIM, 0);
2956        let attrs2 = CellAttrs::new(StyleFlags::DIM, 0);
2957        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
2958        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));
2959
2960        let old = Buffer::new(3, 1);
2961        let diff = BufferDiff::compute(&old, &buffer);
2962
2963        presenter.present(&buffer, &diff).unwrap();
2964        let output = get_output(presenter);
2965        let output_str = String::from_utf8_lossy(&output);
2966
2967        // Should contain bold-off (22) and then dim re-enable (2)
2968        assert!(
2969            output_str.contains("\x1b[22m"),
2970            "Expected bold-off (22) in: {:?}",
2971            output_str
2972        );
2973        assert!(
2974            output_str.contains("\x1b[2m"),
2975            "Expected dim re-enable (2) in: {:?}",
2976            output_str
2977        );
2978    }
2979
2980    #[test]
2981    fn sgr_delta_bold_to_dim_emits_dim_exactly_once() {
2982        // Regression: Bold -> Dim made Dim both "collateral" of the shared
2983        // off-code 22 AND "added", so it was emitted twice (\x1b[2m\x1b[2m)
2984        // and double-counted in the delta estimate.
2985        let mut presenter = test_presenter();
2986        let mut buffer = Buffer::new(3, 1);
2987
2988        let attrs1 = CellAttrs::new(StyleFlags::BOLD, 0);
2989        let attrs2 = CellAttrs::new(StyleFlags::DIM, 0);
2990        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
2991        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));
2992
2993        let old = Buffer::new(3, 1);
2994        let diff = BufferDiff::compute(&old, &buffer);
2995
2996        presenter.present(&buffer, &diff).unwrap();
2997        let output = get_output(presenter);
2998        let output_str = String::from_utf8_lossy(&output);
2999
3000        let dim_count = output_str.matches("\x1b[2m").count();
3001        assert_eq!(
3002            dim_count, 1,
3003            "Dim must be enabled exactly once in: {output_str:?}"
3004        );
3005    }
3006
3007    #[test]
3008    fn emit_diff_runs_arms_wrap_pending_safeguard() {
3009        // Regression: the externally driven entry point (TerminalWriter's
3010        // production path) never set presentation_width, so the tracked
3011        // column was never invalidated at the last cell and drift-repair
3012        // could issue relative moves from a phantom column.
3013        let mut presenter = test_presenter();
3014        let mut buffer = Buffer::new(10, 1);
3015        for x in 0..10 {
3016            buffer.set_raw(x, 0, Cell::from_char('x'));
3017        }
3018        let old = Buffer::new(10, 1);
3019        let diff = BufferDiff::compute(&old, &buffer);
3020
3021        presenter.prepare_runs(&diff);
3022        presenter.emit_diff_runs(&buffer, None, None).unwrap();
3023
3024        assert_eq!(
3025            presenter.presentation_width, 10,
3026            "emit_diff_runs must arm the wrap-pending safeguard"
3027        );
3028        assert_eq!(
3029            presenter.cursor_x, None,
3030            "tracked column must be invalidated after emitting through the last column"
3031        );
3032    }
3033
3034    #[test]
3035    fn sgr_delta_same_style_no_output() {
3036        let mut presenter = test_presenter();
3037        let mut buffer = Buffer::new(3, 1);
3038
3039        let fg = PackedRgba::rgb(255, 0, 0);
3040        let attrs = CellAttrs::new(StyleFlags::BOLD, 0);
3041        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg).with_attrs(attrs));
3042        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg).with_attrs(attrs));
3043        buffer.set_raw(2, 0, Cell::from_char('C').with_fg(fg).with_attrs(attrs));
3044
3045        let old = Buffer::new(3, 1);
3046        let diff = BufferDiff::compute(&old, &buffer);
3047
3048        presenter.present(&buffer, &diff).unwrap();
3049        let output = get_output(presenter);
3050        let output_str = String::from_utf8_lossy(&output);
3051
3052        // Only 1 fg color sequence (style set once for all three cells)
3053        let fg_count = output_str.matches("38;2;255;0;0").count();
3054        assert_eq!(
3055            fg_count, 1,
3056            "Expected 1 fg sequence, got {} in: {:?}",
3057            fg_count, output_str
3058        );
3059    }
3060
3061    #[test]
3062    fn sgr_delta_cost_dominance_never_exceeds_baseline() {
3063        // Test that delta output is never larger than reset+apply would be
3064        // for a variety of style transitions
3065        let transitions: Vec<(CellStyle, CellStyle)> = vec![
3066            // Only fg change
3067            (
3068                CellStyle {
3069                    fg: PackedRgba::rgb(255, 0, 0),
3070                    bg: PackedRgba::TRANSPARENT,
3071                    attrs: StyleFlags::empty(),
3072                },
3073                CellStyle {
3074                    fg: PackedRgba::rgb(0, 255, 0),
3075                    bg: PackedRgba::TRANSPARENT,
3076                    attrs: StyleFlags::empty(),
3077                },
3078            ),
3079            // Only bg change
3080            (
3081                CellStyle {
3082                    fg: PackedRgba::TRANSPARENT,
3083                    bg: PackedRgba::rgb(255, 0, 0),
3084                    attrs: StyleFlags::empty(),
3085                },
3086                CellStyle {
3087                    fg: PackedRgba::TRANSPARENT,
3088                    bg: PackedRgba::rgb(0, 0, 255),
3089                    attrs: StyleFlags::empty(),
3090                },
3091            ),
3092            // Only attr addition
3093            (
3094                CellStyle {
3095                    fg: PackedRgba::rgb(100, 100, 100),
3096                    bg: PackedRgba::TRANSPARENT,
3097                    attrs: StyleFlags::BOLD,
3098                },
3099                CellStyle {
3100                    fg: PackedRgba::rgb(100, 100, 100),
3101                    bg: PackedRgba::TRANSPARENT,
3102                    attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
3103                },
3104            ),
3105            // Attr removal
3106            (
3107                CellStyle {
3108                    fg: PackedRgba::rgb(100, 100, 100),
3109                    bg: PackedRgba::TRANSPARENT,
3110                    attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
3111                },
3112                CellStyle {
3113                    fg: PackedRgba::rgb(100, 100, 100),
3114                    bg: PackedRgba::TRANSPARENT,
3115                    attrs: StyleFlags::BOLD,
3116                },
3117            ),
3118        ];
3119
3120        for (old_style, new_style) in &transitions {
3121            // Measure delta cost
3122            let delta_buf = {
3123                let mut delta_presenter = presenter_for_color_depth(ColorDepth::TrueColor);
3124                delta_presenter.current_style = Some(*old_style);
3125                delta_presenter
3126                    .emit_style_delta(*old_style, *new_style)
3127                    .unwrap();
3128                delta_presenter.into_inner().unwrap()
3129            };
3130
3131            // Measure reset+apply cost
3132            let reset_buf = {
3133                let mut reset_presenter = presenter_for_color_depth(ColorDepth::TrueColor);
3134                reset_presenter.emit_style_full(*new_style).unwrap();
3135                reset_presenter.into_inner().unwrap()
3136            };
3137
3138            assert!(
3139                delta_buf.len() <= reset_buf.len(),
3140                "Delta ({} bytes) exceeded reset+apply ({} bytes) for {:?} -> {:?}.\n\
3141                 Delta: {:?}\nReset: {:?}",
3142                delta_buf.len(),
3143                reset_buf.len(),
3144                old_style,
3145                new_style,
3146                String::from_utf8_lossy(&delta_buf),
3147                String::from_utf8_lossy(&reset_buf),
3148            );
3149        }
3150    }
3151
3152    /// Generate a deterministic JSONL evidence ledger proving the SGR delta engine
3153    /// emits fewer (or equal) bytes than reset+apply for every transition.
3154    ///
3155    /// Each line is a JSON object with:
3156    ///   seed, from_fg, from_bg, from_attrs, to_fg, to_bg, to_attrs,
3157    ///   delta_bytes, baseline_bytes, cost_delta, used_fallback
3158    #[test]
3159    fn sgr_delta_evidence_ledger() {
3160        use std::io::Write as _;
3161
3162        // Deterministic seed for reproducibility
3163        const SEED: u64 = 0xDEAD_BEEF_CAFE;
3164
3165        // Simple LCG for deterministic pseudorandom values
3166        let mut rng_state = SEED;
3167        let mut next_u64 = || -> u64 {
3168            rng_state = rng_state.wrapping_mul(6364136223846793005).wrapping_add(1);
3169            rng_state
3170        };
3171
3172        let random_style = |rng: &mut dyn FnMut() -> u64| -> CellStyle {
3173            let v = rng();
3174            let fg = if v & 1 == 0 {
3175                PackedRgba::TRANSPARENT
3176            } else {
3177                let r = ((v >> 8) & 0xFF) as u8;
3178                let g = ((v >> 16) & 0xFF) as u8;
3179                let b = ((v >> 24) & 0xFF) as u8;
3180                PackedRgba::rgb(r, g, b)
3181            };
3182            let v2 = rng();
3183            let bg = if v2 & 1 == 0 {
3184                PackedRgba::TRANSPARENT
3185            } else {
3186                let r = ((v2 >> 8) & 0xFF) as u8;
3187                let g = ((v2 >> 16) & 0xFF) as u8;
3188                let b = ((v2 >> 24) & 0xFF) as u8;
3189                PackedRgba::rgb(r, g, b)
3190            };
3191            let attrs = StyleFlags::from_bits_truncate(rng() as u8);
3192            CellStyle { fg, bg, attrs }
3193        };
3194
3195        let mut ledger = Vec::new();
3196        let num_transitions = 200;
3197
3198        for i in 0..num_transitions {
3199            let old_style = random_style(&mut next_u64);
3200            let new_style = random_style(&mut next_u64);
3201
3202            // Measure delta cost
3203            let mut delta_p = presenter_for_color_depth(ColorDepth::TrueColor);
3204            delta_p.current_style = Some(old_style);
3205            delta_p.emit_style_delta(old_style, new_style).unwrap();
3206            let delta_out = delta_p.into_inner().unwrap();
3207
3208            // Measure reset+apply cost
3209            let mut reset_p = presenter_for_color_depth(ColorDepth::TrueColor);
3210            reset_p.emit_style_full(new_style).unwrap();
3211            let reset_out = reset_p.into_inner().unwrap();
3212
3213            let delta_bytes = delta_out.len();
3214            let baseline_bytes = reset_out.len();
3215
3216            // Compute whether fallback was used (delta >= baseline means fallback likely)
3217            let attrs_removed = old_style.attrs & !new_style.attrs;
3218            let removed_count = attrs_removed.bits().count_ones();
3219            let fg_changed = old_style.fg != new_style.fg;
3220            let bg_changed = old_style.bg != new_style.bg;
3221            let used_fallback = removed_count >= 3 && fg_changed && bg_changed;
3222
3223            // Assert cost dominance
3224            assert!(
3225                delta_bytes <= baseline_bytes,
3226                "Transition {i}: delta ({delta_bytes}B) > baseline ({baseline_bytes}B)"
3227            );
3228
3229            // Emit JSONL record
3230            writeln!(
3231                &mut ledger,
3232                "{{\"seed\":{SEED},\"i\":{i},\"from_fg\":\"{:?}\",\"from_bg\":\"{:?}\",\
3233                 \"from_attrs\":{},\"to_fg\":\"{:?}\",\"to_bg\":\"{:?}\",\"to_attrs\":{},\
3234                 \"delta_bytes\":{delta_bytes},\"baseline_bytes\":{baseline_bytes},\
3235                 \"cost_delta\":{},\"used_fallback\":{used_fallback}}}",
3236                old_style.fg,
3237                old_style.bg,
3238                old_style.attrs.bits(),
3239                new_style.fg,
3240                new_style.bg,
3241                new_style.attrs.bits(),
3242                baseline_bytes as isize - delta_bytes as isize,
3243            )
3244            .unwrap();
3245        }
3246
3247        // Verify we produced valid JSONL (every line parses)
3248        let text = String::from_utf8(ledger).unwrap();
3249        let lines: Vec<&str> = text.lines().collect();
3250        assert_eq!(lines.len(), num_transitions);
3251
3252        // Verify aggregate: total savings should be non-negative
3253        let mut total_saved: isize = 0;
3254        for line in &lines {
3255            // Quick parse of cost_delta field
3256            let cd_start = line.find("\"cost_delta\":").unwrap() + 13;
3257            let cd_end = line[cd_start..].find(',').unwrap() + cd_start;
3258            let cd: isize = line[cd_start..cd_end].parse().unwrap();
3259            total_saved += cd;
3260        }
3261        assert!(
3262            total_saved >= 0,
3263            "Total byte savings should be non-negative, got {total_saved}"
3264        );
3265    }
3266
3267    /// E2E style stress test: scripted style churn across a full buffer
3268    /// with byte metrics proving delta engine correctness under load.
3269    #[test]
3270    fn e2e_style_stress_with_byte_metrics() {
3271        let width = 40u16;
3272        let height = 10u16;
3273
3274        // Build a buffer with maximum style diversity
3275        let mut buffer = Buffer::new(width, height);
3276        for y in 0..height {
3277            for x in 0..width {
3278                let i = (y as usize * width as usize + x as usize) as u8;
3279                let fg = PackedRgba::rgb(i, 255 - i, i.wrapping_mul(3));
3280                let bg = if i.is_multiple_of(4) {
3281                    PackedRgba::rgb(i.wrapping_mul(7), i.wrapping_mul(11), i.wrapping_mul(13))
3282                } else {
3283                    PackedRgba::TRANSPARENT
3284                };
3285                let flags = StyleFlags::from_bits_truncate(i % 128);
3286                let ch = char::from_u32(('!' as u32) + (i as u32 % 90)).unwrap_or('?');
3287                let cell = Cell::from_char(ch)
3288                    .with_fg(fg)
3289                    .with_bg(bg)
3290                    .with_attrs(CellAttrs::new(flags, 0));
3291                buffer.set_raw(x, y, cell);
3292            }
3293        }
3294
3295        // Present from blank (first frame)
3296        let blank = Buffer::new(width, height);
3297        let diff = BufferDiff::compute(&blank, &buffer);
3298        let mut presenter = test_presenter();
3299        presenter.present(&buffer, &diff).unwrap();
3300        let frame1_bytes = presenter.into_inner().unwrap().len();
3301
3302        // Build second buffer: shift all styles by one position (churn)
3303        let mut buffer2 = Buffer::new(width, height);
3304        for y in 0..height {
3305            for x in 0..width {
3306                let i = (y as usize * width as usize + x as usize + 1) as u8;
3307                let fg = PackedRgba::rgb(i, 255 - i, i.wrapping_mul(3));
3308                let bg = if i.is_multiple_of(4) {
3309                    PackedRgba::rgb(i.wrapping_mul(7), i.wrapping_mul(11), i.wrapping_mul(13))
3310                } else {
3311                    PackedRgba::TRANSPARENT
3312                };
3313                let flags = StyleFlags::from_bits_truncate(i % 128);
3314                let ch = char::from_u32(('!' as u32) + (i as u32 % 90)).unwrap_or('?');
3315                let cell = Cell::from_char(ch)
3316                    .with_fg(fg)
3317                    .with_bg(bg)
3318                    .with_attrs(CellAttrs::new(flags, 0));
3319                buffer2.set_raw(x, y, cell);
3320            }
3321        }
3322
3323        // Second frame: incremental update should use delta engine
3324        let diff2 = BufferDiff::compute(&buffer, &buffer2);
3325        let mut presenter2 = test_presenter();
3326        presenter2.present(&buffer2, &diff2).unwrap();
3327        let frame2_bytes = presenter2.into_inner().unwrap().len();
3328
3329        // Incremental should be smaller than full redraw since delta
3330        // engine can reuse partial style state
3331        assert!(
3332            frame2_bytes > 0,
3333            "Second frame should produce output for style churn"
3334        );
3335        assert!(!diff2.is_empty(), "Style shift should produce changes");
3336
3337        // Verify frame2 is at most frame1 size (delta should never be worse
3338        // than a full redraw for the same number of changed cells)
3339        // Note: frame2 may differ in size due to different diff (changed cells
3340        // vs all cells), so just verify it's reasonable.
3341        assert!(
3342            frame2_bytes <= frame1_bytes * 2,
3343            "Incremental frame ({frame2_bytes}B) unreasonably large vs full ({frame1_bytes}B)"
3344        );
3345    }
3346
3347    // =========================================================================
3348    // DP Cost Model Tests (bd-4kq0.2.2)
3349    // =========================================================================
3350
3351    #[test]
3352    fn cost_model_empty_row_single_run() {
3353        // Single run on a row should always use Sparse (no merge benefit)
3354        let runs = [ChangeRun::new(5, 10, 20)];
3355        let plan = cost_model::plan_row(&runs, None, None);
3356        assert_eq!(plan.spans().len(), 1);
3357        assert_eq!(plan.spans()[0].x0, 10);
3358        assert_eq!(plan.spans()[0].x1, 20);
3359        assert!(plan.total_cost() > 0);
3360    }
3361
3362    #[test]
3363    fn cost_model_full_row_merges() {
3364        // Two small runs far apart on same row - gap is smaller than 2x CUP overhead
3365        // Runs at columns 0-2 and 77-79 on an 80-col row
3366        // Sparse: CUP + 3 cells + CUP + 3 cells
3367        // Merged: CUP + 80 cells but with gap overhead
3368        // This should stay sparse since the gap is very large
3369        let runs = [ChangeRun::new(0, 0, 2), ChangeRun::new(0, 77, 79)];
3370        let plan = cost_model::plan_row(&runs, None, None);
3371        // Large gap (74 cells * 2 overhead = 148) vs CUP savings (~8) => no merge.
3372        assert_eq!(plan.spans().len(), 2);
3373        assert_eq!(plan.spans()[0].x0, 0);
3374        assert_eq!(plan.spans()[0].x1, 2);
3375        assert_eq!(plan.spans()[1].x0, 77);
3376        assert_eq!(plan.spans()[1].x1, 79);
3377    }
3378
3379    #[test]
3380    fn cost_model_adjacent_runs_merge() {
3381        // Many single-cell runs with 1-cell gaps should merge
3382        // 8 single-cell runs at columns 10, 12, 14, 16, 18, 20, 22, 24
3383        let runs = [
3384            ChangeRun::new(3, 10, 10),
3385            ChangeRun::new(3, 12, 12),
3386            ChangeRun::new(3, 14, 14),
3387            ChangeRun::new(3, 16, 16),
3388            ChangeRun::new(3, 18, 18),
3389            ChangeRun::new(3, 20, 20),
3390            ChangeRun::new(3, 22, 22),
3391            ChangeRun::new(3, 24, 24),
3392        ];
3393        let plan = cost_model::plan_row(&runs, None, None);
3394        // Sparse: 1 CUP + 7 CUF(2) * 4 bytes + 8 cells = ~7+28+8 = 43
3395        // Merged: 1 CUP + 8 changed + 7 gap * 2 = 7+8+14 = 29
3396        assert_eq!(plan.spans().len(), 1);
3397        assert_eq!(plan.spans()[0].x0, 10);
3398        assert_eq!(plan.spans()[0].x1, 24);
3399    }
3400
3401    #[test]
3402    fn cost_model_single_cell_stays_sparse() {
3403        let runs = [ChangeRun::new(0, 40, 40)];
3404        let plan = cost_model::plan_row(&runs, Some(0), Some(0));
3405        assert_eq!(plan.spans().len(), 1);
3406        assert_eq!(plan.spans()[0].x0, 40);
3407        assert_eq!(plan.spans()[0].x1, 40);
3408    }
3409
3410    #[test]
3411    fn cost_model_cup_vs_cha_vs_cuf() {
3412        // CUF should be cheapest for small forward moves on same row
3413        assert!(cost_model::cuf_cost(1) <= cost_model::cha_cost(5));
3414        assert!(cost_model::cuf_cost(3) <= cost_model::cup_cost(0, 5));
3415
3416        // CHA should be cheapest for backward moves on same row (vs CUP)
3417        let cha = cost_model::cha_cost(5);
3418        let cup = cost_model::cup_cost(0, 5);
3419        assert!(cha <= cup);
3420
3421        // Cheapest move from known position (same row, forward 1)
3422        let cost = cost_model::cheapest_move_cost(Some(5), Some(0), 6, 0);
3423        assert_eq!(cost, 3); // CUF(1) = "\x1b[C" = 3 bytes
3424    }
3425
3426    #[test]
3427    fn cost_model_digit_estimation_accuracy() {
3428        // Verify CUP cost estimates are accurate by comparing to actual output
3429        let mut buf = Vec::new();
3430        ansi::cup(&mut buf, 0, 0).unwrap();
3431        assert_eq!(buf.len(), cost_model::cup_cost(0, 0));
3432
3433        buf.clear();
3434        ansi::cup(&mut buf, 9, 9).unwrap();
3435        assert_eq!(buf.len(), cost_model::cup_cost(9, 9));
3436
3437        buf.clear();
3438        ansi::cup(&mut buf, 99, 99).unwrap();
3439        assert_eq!(buf.len(), cost_model::cup_cost(99, 99));
3440
3441        buf.clear();
3442        ansi::cha(&mut buf, 0).unwrap();
3443        assert_eq!(buf.len(), cost_model::cha_cost(0));
3444
3445        buf.clear();
3446        ansi::cuf(&mut buf, 1).unwrap();
3447        assert_eq!(buf.len(), cost_model::cuf_cost(1));
3448
3449        buf.clear();
3450        ansi::cuf(&mut buf, 10).unwrap();
3451        assert_eq!(buf.len(), cost_model::cuf_cost(10));
3452    }
3453
3454    #[test]
3455    fn cost_model_merged_row_produces_correct_output() {
3456        // Verify that merged emission produces the same visual result as sparse
3457        let width = 30u16;
3458        let mut buffer = Buffer::new(width, 1);
3459
3460        // Set up scattered changes: columns 5, 10, 15, 20
3461        for col in [5u16, 10, 15, 20] {
3462            let ch = char::from_u32('A' as u32 + col as u32 % 26).unwrap();
3463            buffer.set_raw(col, 0, Cell::from_char(ch));
3464        }
3465
3466        let old = Buffer::new(width, 1);
3467        let diff = BufferDiff::compute(&old, &buffer);
3468
3469        // Present and verify output contains expected characters
3470        let mut presenter = test_presenter();
3471        presenter.present(&buffer, &diff).unwrap();
3472        let output = presenter.into_inner().unwrap();
3473        let output_str = String::from_utf8_lossy(&output);
3474
3475        for col in [5u16, 10, 15, 20] {
3476            let ch = char::from_u32('A' as u32 + col as u32 % 26).unwrap();
3477            assert!(
3478                output_str.contains(ch),
3479                "Missing character '{ch}' at col {col} in output"
3480            );
3481        }
3482    }
3483
3484    #[test]
3485    fn cost_model_optimal_cursor_uses_cuf_on_same_row() {
3486        // Verify move_cursor_optimal uses CUF for small forward moves
3487        let mut presenter = test_presenter();
3488        presenter.cursor_x = Some(5);
3489        presenter.cursor_y = Some(0);
3490        presenter.move_cursor_optimal(6, 0).unwrap();
3491        let output = presenter.into_inner().unwrap();
3492        // CUF(1) = "\x1b[C"
3493        assert_eq!(&output, b"\x1b[C", "Should use CUF for +1 column move");
3494    }
3495
3496    #[test]
3497    fn cost_model_optimal_cursor_uses_cha_on_same_row_backward() {
3498        let mut presenter = test_presenter();
3499        presenter.cursor_x = Some(10);
3500        presenter.cursor_y = Some(3);
3501
3502        let target_x = 2;
3503        let target_y = 3;
3504        let cha_cost = cost_model::cha_cost(target_x);
3505        let cup_cost = cost_model::cup_cost(target_y, target_x);
3506        assert!(
3507            cha_cost <= cup_cost,
3508            "Expected CHA to be cheaper for backward move (cha={cha_cost}, cup={cup_cost})"
3509        );
3510
3511        presenter.move_cursor_optimal(target_x, target_y).unwrap();
3512        let output = presenter.into_inner().unwrap();
3513        let mut expected = Vec::new();
3514        ansi::cha(&mut expected, target_x).unwrap();
3515        assert_eq!(output, expected, "Should use CHA for backward move");
3516    }
3517
3518    #[test]
3519    fn cost_model_optimal_cursor_uses_cup_on_row_change() {
3520        let mut presenter = test_presenter();
3521        presenter.cursor_x = Some(4);
3522        presenter.cursor_y = Some(1);
3523
3524        presenter.move_cursor_optimal(7, 4).unwrap();
3525        let output = presenter.into_inner().unwrap();
3526        let mut expected = Vec::new();
3527        ansi::cup(&mut expected, 4, 7).unwrap();
3528        assert_eq!(output, expected, "Should use CUP when row changes");
3529    }
3530
3531    #[test]
3532    fn cost_model_chooses_full_row_when_cheaper() {
3533        // Create a scenario where merged is definitely cheaper:
3534        // 10 single-cell runs with 1-cell gaps on the same row
3535        let width = 40u16;
3536        let mut buffer = Buffer::new(width, 1);
3537
3538        // Every other column: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18
3539        for col in (0..20).step_by(2) {
3540            buffer.set_raw(col, 0, Cell::from_char('X'));
3541        }
3542
3543        let old = Buffer::new(width, 1);
3544        let diff = BufferDiff::compute(&old, &buffer);
3545        let runs = diff.runs();
3546
3547        // The cost model should merge (many small gaps < many CUP costs)
3548        let row_runs: Vec<_> = runs.iter().filter(|r| r.y == 0).copied().collect();
3549        if row_runs.len() > 1 {
3550            let plan = cost_model::plan_row(&row_runs, None, None);
3551            assert!(
3552                plan.spans().len() == 1,
3553                "Expected single merged span for many small runs, got {} spans",
3554                plan.spans().len()
3555            );
3556            assert_eq!(plan.spans()[0].x0, 0);
3557            assert_eq!(plan.spans()[0].x1, 18);
3558        }
3559    }
3560
3561    #[test]
3562    fn perf_cost_model_overhead() {
3563        // Verify the cost model planning is fast (microsecond scale)
3564        use std::time::Instant;
3565
3566        let runs: Vec<ChangeRun> = (0..100)
3567            .map(|i| ChangeRun::new(0, i * 3, i * 3 + 1))
3568            .collect();
3569
3570        let (iterations, max_ms) = if cfg!(debug_assertions) {
3571            (1_000, 1_000u128)
3572        } else {
3573            (10_000, 500u128)
3574        };
3575
3576        let start = Instant::now();
3577        for _ in 0..iterations {
3578            let _ = cost_model::plan_row(&runs, None, None);
3579        }
3580        let elapsed = start.elapsed();
3581
3582        // Keep this generous in debug builds to avoid flaky perf assertions.
3583        assert!(
3584            elapsed.as_millis() < max_ms,
3585            "Cost model planning too slow: {elapsed:?} for {iterations} iterations"
3586        );
3587    }
3588
3589    #[test]
3590    fn perf_legacy_vs_dp_worst_case_sparse() {
3591        use std::time::Instant;
3592
3593        let width = 200u16;
3594        let height = 1u16;
3595        let mut buffer = Buffer::new(width, height);
3596
3597        // Two dense clusters with a large gap between them.
3598        for col in (0..40).step_by(2) {
3599            buffer.set_raw(col, 0, Cell::from_char('X'));
3600        }
3601        for col in (160..200).step_by(2) {
3602            buffer.set_raw(col, 0, Cell::from_char('Y'));
3603        }
3604
3605        let blank = Buffer::new(width, height);
3606        let diff = BufferDiff::compute(&blank, &buffer);
3607        let runs = diff.runs();
3608        let row_runs: Vec<_> = runs.iter().filter(|r| r.y == 0).copied().collect();
3609
3610        let dp_plan = cost_model::plan_row(&row_runs, None, None);
3611        let legacy_spans = legacy_plan_row(&row_runs, None, None);
3612
3613        let dp_output = emit_spans_for_output(&buffer, dp_plan.spans());
3614        let legacy_output = emit_spans_for_output(&buffer, &legacy_spans);
3615
3616        assert!(
3617            dp_output.len() <= legacy_output.len(),
3618            "DP output should be <= legacy output (dp={}, legacy={})",
3619            dp_output.len(),
3620            legacy_output.len()
3621        );
3622
3623        let (iterations, max_ms) = if cfg!(debug_assertions) {
3624            (1_000, 1_000u128)
3625        } else {
3626            (10_000, 500u128)
3627        };
3628        let start = Instant::now();
3629        for _ in 0..iterations {
3630            let _ = cost_model::plan_row(&row_runs, None, None);
3631        }
3632        let dp_elapsed = start.elapsed();
3633
3634        let start = Instant::now();
3635        for _ in 0..iterations {
3636            let _ = legacy_plan_row(&row_runs, None, None);
3637        }
3638        let legacy_elapsed = start.elapsed();
3639
3640        assert!(
3641            dp_elapsed.as_millis() < max_ms,
3642            "DP planning too slow: {dp_elapsed:?} for {iterations} iterations"
3643        );
3644
3645        let _ = legacy_elapsed;
3646    }
3647
3648    // =========================================================================
3649    // Presenter Perf + Golden Outputs (bd-4kq0.2.3)
3650    // =========================================================================
3651
3652    /// Build a deterministic "style-heavy" scene: every cell has a unique style.
3653    fn build_style_heavy_scene(width: u16, height: u16, seed: u64) -> Buffer {
3654        let mut buffer = Buffer::new(width, height);
3655        let mut rng = seed;
3656        let mut next = || -> u64 {
3657            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
3658            rng
3659        };
3660        for y in 0..height {
3661            for x in 0..width {
3662                let v = next();
3663                let ch = char::from_u32(('!' as u32) + (v as u32 % 90)).unwrap_or('?');
3664                let fg = PackedRgba::rgb((v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8);
3665                let bg = if v & 3 == 0 {
3666                    PackedRgba::rgb((v >> 32) as u8, (v >> 40) as u8, (v >> 48) as u8)
3667                } else {
3668                    PackedRgba::TRANSPARENT
3669                };
3670                let flags = StyleFlags::from_bits_truncate((v >> 56) as u8);
3671                let cell = Cell::from_char(ch)
3672                    .with_fg(fg)
3673                    .with_bg(bg)
3674                    .with_attrs(CellAttrs::new(flags, 0));
3675                buffer.set_raw(x, y, cell);
3676            }
3677        }
3678        buffer
3679    }
3680
3681    /// Build a "sparse-update" scene: only ~10% of cells differ between frames.
3682    fn build_sparse_update(base: &Buffer, seed: u64) -> Buffer {
3683        let mut buffer = base.clone();
3684        let width = base.width();
3685        let height = base.height();
3686        let mut rng = seed;
3687        let mut next = || -> u64 {
3688            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
3689            rng
3690        };
3691        let change_count = (width as usize * height as usize) / 10;
3692        for _ in 0..change_count {
3693            let v = next();
3694            let x = (v % width as u64) as u16;
3695            let y = ((v >> 16) % height as u64) as u16;
3696            let ch = char::from_u32(('A' as u32) + (v as u32 % 26)).unwrap_or('?');
3697            buffer.set_raw(x, y, Cell::from_char(ch));
3698        }
3699        buffer
3700    }
3701
3702    #[test]
3703    fn snapshot_presenter_equivalence() {
3704        // Golden snapshot: style-heavy 40x10 scene with deterministic seed.
3705        // The output hash must be stable across runs.
3706        let buffer = build_style_heavy_scene(40, 10, 0xDEAD_CAFE_1234);
3707        let blank = Buffer::new(40, 10);
3708        let diff = BufferDiff::compute(&blank, &buffer);
3709
3710        let mut presenter = test_presenter();
3711        presenter.present(&buffer, &diff).unwrap();
3712        let output = presenter.into_inner().unwrap();
3713
3714        // Compute checksum for golden comparison
3715        let checksum = {
3716            let mut hash: u64 = 0xcbf29ce484222325; // FNV-1a offset basis
3717            for &byte in &output {
3718                hash ^= byte as u64;
3719                hash = hash.wrapping_mul(0x100000001b3); // FNV prime
3720            }
3721            hash
3722        };
3723
3724        // Verify determinism: same seed + scene = same output
3725        let mut presenter2 = test_presenter();
3726        presenter2.present(&buffer, &diff).unwrap();
3727        let output2 = presenter2.into_inner().unwrap();
3728        assert_eq!(output, output2, "Presenter output must be deterministic");
3729
3730        // Log golden checksum for the record
3731        let _ = checksum; // Used in JSONL test below
3732    }
3733
3734    #[test]
3735    fn perf_presenter_microbench() {
3736        use std::env;
3737        use std::io::Write as _;
3738        use std::time::Instant;
3739
3740        let width = 120u16;
3741        let height = 40u16;
3742        let seed = 0x00BE_EFCA_FE42;
3743        let scene = build_style_heavy_scene(width, height, seed);
3744        let blank = Buffer::new(width, height);
3745        let diff_full = BufferDiff::compute(&blank, &scene);
3746
3747        // Also build a sparse update scene
3748        let scene2 = build_sparse_update(&scene, seed.wrapping_add(1));
3749        let diff_sparse = BufferDiff::compute(&scene, &scene2);
3750
3751        let mut jsonl = Vec::new();
3752        let iterations = env::var("FTUI_PRESENTER_BENCH_ITERS")
3753            .ok()
3754            .and_then(|value| value.parse::<u32>().ok())
3755            .unwrap_or(50);
3756
3757        let runs_full = diff_full.runs();
3758        let runs_sparse = diff_sparse.runs();
3759
3760        let plan_rows = |runs: &[ChangeRun]| -> (usize, usize) {
3761            let mut idx = 0;
3762            let mut total_cost = 0usize;
3763            let mut span_count = 0usize;
3764            let mut prev_x = None;
3765            let mut prev_y = None;
3766
3767            while idx < runs.len() {
3768                let y = runs[idx].y;
3769                let start = idx;
3770                while idx < runs.len() && runs[idx].y == y {
3771                    idx += 1;
3772                }
3773
3774                let plan = cost_model::plan_row(&runs[start..idx], prev_x, prev_y);
3775                span_count += plan.spans().len();
3776                total_cost = total_cost.saturating_add(plan.total_cost());
3777                if let Some(last) = plan.spans().last() {
3778                    prev_x = Some(last.x1);
3779                    prev_y = Some(y);
3780                }
3781            }
3782
3783            (total_cost, span_count)
3784        };
3785
3786        for i in 0..iterations {
3787            let (diff_ref, buf_ref, runs_ref, label) = if i % 2 == 0 {
3788                (&diff_full, &scene, &runs_full, "full")
3789            } else {
3790                (&diff_sparse, &scene2, &runs_sparse, "sparse")
3791            };
3792
3793            let plan_start = Instant::now();
3794            let (plan_cost, plan_spans) = plan_rows(runs_ref);
3795            let plan_time_us = plan_start.elapsed().as_micros() as u64;
3796
3797            let mut presenter = test_presenter();
3798            let start = Instant::now();
3799            let stats = presenter.present(buf_ref, diff_ref).unwrap();
3800            let elapsed_us = start.elapsed().as_micros() as u64;
3801            let output = presenter.into_inner().unwrap();
3802
3803            // FNV-1a checksum
3804            let checksum = {
3805                let mut hash: u64 = 0xcbf29ce484222325;
3806                for &b in &output {
3807                    hash ^= b as u64;
3808                    hash = hash.wrapping_mul(0x100000001b3);
3809                }
3810                hash
3811            };
3812
3813            writeln!(
3814                &mut jsonl,
3815                "{{\"seed\":{seed},\"width\":{width},\"height\":{height},\
3816                 \"scene\":\"{label}\",\"changes\":{},\"runs\":{},\
3817                 \"plan_cost\":{plan_cost},\"plan_spans\":{plan_spans},\
3818                 \"plan_time_us\":{plan_time_us},\"bytes\":{},\
3819                 \"emit_time_us\":{elapsed_us},\
3820                 \"checksum\":\"{checksum:016x}\"}}",
3821                stats.cells_changed, stats.run_count, stats.bytes_emitted,
3822            )
3823            .unwrap();
3824        }
3825
3826        let text = String::from_utf8(jsonl).unwrap();
3827        let lines: Vec<&str> = text.lines().collect();
3828        assert_eq!(lines.len(), iterations as usize);
3829
3830        // Parse and verify: full frames should be deterministic (same checksum)
3831        let full_checksums: Vec<&str> = lines
3832            .iter()
3833            .filter(|l| l.contains("\"full\""))
3834            .map(|l| {
3835                let start = l.find("\"checksum\":\"").unwrap() + 12;
3836                let end = l[start..].find('"').unwrap() + start;
3837                &l[start..end]
3838            })
3839            .collect();
3840        assert!(full_checksums.len() > 1);
3841        assert!(
3842            full_checksums.windows(2).all(|w| w[0] == w[1]),
3843            "Full frame checksums should be identical across runs"
3844        );
3845
3846        // Sparse frame bytes should be less than full frame bytes
3847        let full_bytes: Vec<u64> = lines
3848            .iter()
3849            .filter(|l| l.contains("\"full\""))
3850            .map(|l| {
3851                let start = l.find("\"bytes\":").unwrap() + 8;
3852                let end = l[start..].find(',').unwrap() + start;
3853                l[start..end].parse::<u64>().unwrap()
3854            })
3855            .collect();
3856        let sparse_bytes: Vec<u64> = lines
3857            .iter()
3858            .filter(|l| l.contains("\"sparse\""))
3859            .map(|l| {
3860                let start = l.find("\"bytes\":").unwrap() + 8;
3861                let end = l[start..].find(',').unwrap() + start;
3862                l[start..end].parse::<u64>().unwrap()
3863            })
3864            .collect();
3865
3866        let avg_full: u64 = full_bytes.iter().sum::<u64>() / full_bytes.len() as u64;
3867        let avg_sparse: u64 = sparse_bytes.iter().sum::<u64>() / sparse_bytes.len() as u64;
3868        assert!(
3869            avg_sparse < avg_full,
3870            "Sparse updates ({avg_sparse}B) should emit fewer bytes than full ({avg_full}B)"
3871        );
3872    }
3873
3874    #[test]
3875    fn perf_emit_style_delta_microbench() {
3876        use std::env;
3877        use std::io::Write as _;
3878        use std::time::Instant;
3879
3880        let iterations = env::var("FTUI_EMIT_STYLE_BENCH_ITERS")
3881            .ok()
3882            .and_then(|value| value.parse::<u32>().ok())
3883            .unwrap_or(200);
3884        let mode = env::var("FTUI_EMIT_STYLE_BENCH_MODE").unwrap_or_default();
3885        let emit_json = mode != "raw";
3886
3887        let mut styles = Vec::with_capacity(128);
3888        let mut rng = 0x00A5_A51E_AF42_u64;
3889        let mut next = || -> u64 {
3890            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
3891            rng
3892        };
3893
3894        for _ in 0..128 {
3895            let v = next();
3896            let fg = PackedRgba::rgb(
3897                (v & 0xFF) as u8,
3898                ((v >> 8) & 0xFF) as u8,
3899                ((v >> 16) & 0xFF) as u8,
3900            );
3901            let bg = PackedRgba::rgb(
3902                ((v >> 24) & 0xFF) as u8,
3903                ((v >> 32) & 0xFF) as u8,
3904                ((v >> 40) & 0xFF) as u8,
3905            );
3906            let flags = StyleFlags::from_bits_truncate((v >> 48) as u8);
3907            let cell = Cell::from_char('A')
3908                .with_fg(fg)
3909                .with_bg(bg)
3910                .with_attrs(CellAttrs::new(flags, 0));
3911            styles.push(CellStyle::from_cell(&cell));
3912        }
3913
3914        let mut presenter = test_presenter();
3915        let mut jsonl = Vec::new();
3916        let mut sink = 0u64;
3917
3918        for i in 0..iterations {
3919            let old = styles[i as usize % styles.len()];
3920            let new = styles[(i as usize + 1) % styles.len()];
3921
3922            presenter.writer.reset_counter();
3923            presenter.writer.inner_mut().get_mut().clear();
3924
3925            let start = Instant::now();
3926            presenter.emit_style_delta(old, new).unwrap();
3927            let elapsed_us = start.elapsed().as_micros() as u64;
3928            let bytes = presenter.writer.bytes_written();
3929
3930            if emit_json {
3931                writeln!(
3932                    &mut jsonl,
3933                    "{{\"iter\":{i},\"emit_time_us\":{elapsed_us},\"bytes\":{bytes}}}"
3934                )
3935                .unwrap();
3936            } else {
3937                sink = sink.wrapping_add(elapsed_us ^ bytes);
3938            }
3939        }
3940
3941        if emit_json {
3942            let text = String::from_utf8(jsonl).unwrap();
3943            let lines: Vec<&str> = text.lines().collect();
3944            assert_eq!(lines.len() as u32, iterations);
3945        } else {
3946            std::hint::black_box(sink);
3947        }
3948    }
3949
3950    #[test]
3951    fn e2e_presenter_stress_deterministic() {
3952        // Deterministic stress test: seeded style churn across multiple frames,
3953        // verifying no visual divergence via terminal model.
3954        use crate::terminal_model::TerminalModel;
3955
3956        let width = 60u16;
3957        let height = 20u16;
3958        let num_frames = 10;
3959
3960        let mut prev_buffer = Buffer::new(width, height);
3961        let mut presenter = test_presenter();
3962        let mut model = TerminalModel::new(width as usize, height as usize);
3963        let mut rng = 0x5D2E_55DE_5D42_u64;
3964        let mut next = || -> u64 {
3965            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
3966            rng
3967        };
3968
3969        for _frame in 0..num_frames {
3970            // Build next frame: modify ~20% of cells each time
3971            let mut buffer = prev_buffer.clone();
3972            let changes = (width as usize * height as usize) / 5;
3973            for _ in 0..changes {
3974                let v = next();
3975                let x = (v % width as u64) as u16;
3976                let y = ((v >> 16) % height as u64) as u16;
3977                let ch = char::from_u32(('!' as u32) + (v as u32 % 90)).unwrap_or('?');
3978                let fg = PackedRgba::rgb((v >> 8) as u8, (v >> 24) as u8, (v >> 40) as u8);
3979                let cell = Cell::from_char(ch).with_fg(fg);
3980                buffer.set_raw(x, y, cell);
3981            }
3982
3983            let diff = BufferDiff::compute(&prev_buffer, &buffer);
3984            presenter.present(&buffer, &diff).unwrap();
3985
3986            prev_buffer = buffer;
3987        }
3988
3989        // Get all output and verify final frame via terminal model
3990        let output = presenter.into_inner().unwrap();
3991        model.process(&output);
3992
3993        // Every cell matches the final buffer. This accepted 80% of the
3994        // non-empty cells, blaming "cursor positioning sequences"; nothing
3995        // overwrites them, and a random multi-frame probe (wide characters,
3996        // truecolor, style flags) matched every cell of every frame.
3997        let mut checked = 0;
3998        let mut total_nonempty = 0;
3999        for y in 0..height {
4000            for x in 0..width {
4001                let buf_cell = prev_buffer.get_unchecked(x, y);
4002                if !buf_cell.is_empty()
4003                    && let Some(model_cell) = model.cell(x as usize, y as usize)
4004                {
4005                    total_nonempty += 1;
4006                    let expected = buf_cell.content.as_char().unwrap_or(' ');
4007                    let mut buf = [0u8; 4];
4008                    let expected_str = expected.encode_utf8(&mut buf);
4009                    if model_cell.text.as_str() == expected_str && model_cell.fg == buf_cell.fg {
4010                        checked += 1;
4011                    }
4012                }
4013            }
4014        }
4015
4016        assert!(
4017            total_nonempty > 0 && checked == total_nonempty,
4018            "Frame {num_frames}: only {checked}/{total_nonempty} cells match final buffer"
4019        );
4020    }
4021
4022    #[test]
4023    fn style_state_persists_across_frames() {
4024        let mut presenter = test_presenter();
4025        let fg = PackedRgba::rgb(100, 150, 200);
4026
4027        // First frame - set style
4028        let mut buffer = Buffer::new(5, 1);
4029        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg));
4030        let old = Buffer::new(5, 1);
4031        let diff = BufferDiff::compute(&old, &buffer);
4032        presenter.present(&buffer, &diff).unwrap();
4033
4034        // Style should be tracked (but reset at frame end per the implementation)
4035        // After present(), current_style is None due to sgr_reset at frame end
4036        assert!(
4037            presenter.current_style.is_none(),
4038            "Style should be reset after frame end"
4039        );
4040    }
4041
4042    // =========================================================================
4043    // Edge-case tests (bd-27tya)
4044    // =========================================================================
4045
4046    // --- Cost model boundary values ---
4047
4048    #[test]
4049    fn cost_cup_zero_zero() {
4050        // CUP at (0,0) → "\x1b[1;1H" = 6 bytes
4051        assert_eq!(cost_model::cup_cost(0, 0), 6);
4052    }
4053
4054    #[test]
4055    fn cost_cup_max_max() {
4056        // CUP at (u16::MAX, u16::MAX) → "\x1b[65536;65536H"
4057        // 2 (CSI) + 5 (row digits) + 1 (;) + 5 (col digits) + 1 (H) = 14
4058        assert_eq!(cost_model::cup_cost(u16::MAX, u16::MAX), 14);
4059    }
4060
4061    #[test]
4062    fn cost_cha_zero() {
4063        // CHA at col 0 → "\x1b[1G" = 4 bytes
4064        assert_eq!(cost_model::cha_cost(0), 4);
4065    }
4066
4067    #[test]
4068    fn cost_cha_max() {
4069        // CHA at col u16::MAX → "\x1b[65536G" = 8 bytes
4070        assert_eq!(cost_model::cha_cost(u16::MAX), 8);
4071    }
4072
4073    #[test]
4074    fn cost_cuf_zero_is_free() {
4075        assert_eq!(cost_model::cuf_cost(0), 0);
4076    }
4077
4078    #[test]
4079    fn cost_cuf_one_is_three() {
4080        // CUF(1) = "\x1b[C" = 3 bytes
4081        assert_eq!(cost_model::cuf_cost(1), 3);
4082    }
4083
4084    #[test]
4085    fn cost_cuf_two_has_digit() {
4086        // CUF(2) = "\x1b[2C" = 4 bytes
4087        assert_eq!(cost_model::cuf_cost(2), 4);
4088    }
4089
4090    #[test]
4091    fn cost_cuf_max() {
4092        // CUF(u16::MAX) = "\x1b[65535C" = 3 + 5 = 8 bytes
4093        assert_eq!(cost_model::cuf_cost(u16::MAX), 8);
4094    }
4095
4096    #[test]
4097    fn cost_cheapest_move_already_at_target() {
4098        assert_eq!(cost_model::cheapest_move_cost(Some(5), Some(3), 5, 3), 0);
4099    }
4100
4101    #[test]
4102    fn cost_cheapest_move_unknown_position() {
4103        // When from is unknown, can only use CUP
4104        let cost = cost_model::cheapest_move_cost(None, None, 5, 3);
4105        assert_eq!(cost, cost_model::cup_cost(3, 5));
4106    }
4107
4108    #[test]
4109    fn cost_cheapest_move_known_y_unknown_x() {
4110        // from_x=None, from_y=Some → still uses CUP
4111        let cost = cost_model::cheapest_move_cost(None, Some(3), 5, 3);
4112        assert_eq!(cost, cost_model::cup_cost(3, 5));
4113    }
4114
4115    #[test]
4116    fn cost_cheapest_move_backward_same_row() {
4117        // On the same row, CUP is strictly dominated by CHA.
4118        let cost = cost_model::cheapest_move_cost(Some(50), Some(0), 5, 0);
4119        let cha = cost_model::cha_cost(5);
4120        let cub = cost_model::cub_cost(45);
4121        assert_eq!(cost, cha.min(cub));
4122        assert!(cost_model::cup_cost(0, 5) > cha);
4123    }
4124
4125    #[test]
4126    fn cost_cheapest_move_forward_same_row() {
4127        let cost = cost_model::cheapest_move_cost(Some(5), Some(0), 50, 0);
4128        let cha = cost_model::cha_cost(50);
4129        let cuf = cost_model::cuf_cost(45);
4130        assert_eq!(cost, cha.min(cuf));
4131        assert!(cost_model::cup_cost(0, 50) > cha);
4132    }
4133
4134    #[test]
4135    fn cost_cheapest_move_same_row_same_col() {
4136        // Same (x, y) via the (fx, fy) == (to_x, to_y) check
4137        assert_eq!(cost_model::cheapest_move_cost(Some(0), Some(0), 0, 0), 0);
4138    }
4139
4140    // --- CUP/CHA/CUF cost accuracy across digit boundaries ---
4141
4142    #[test]
4143    fn cost_cup_digit_boundaries() {
4144        let mut buf = Vec::new();
4145        for (row, col) in [
4146            (0u16, 0u16),
4147            (8, 8),
4148            (9, 9),
4149            (98, 98),
4150            (99, 99),
4151            (998, 998),
4152            (999, 999),
4153            (9998, 9998),
4154            (9999, 9999),
4155            (u16::MAX, u16::MAX),
4156        ] {
4157            buf.clear();
4158            ansi::cup(&mut buf, row, col).unwrap();
4159            assert_eq!(
4160                buf.len(),
4161                cost_model::cup_cost(row, col),
4162                "CUP cost mismatch at ({row}, {col})"
4163            );
4164        }
4165    }
4166
4167    #[test]
4168    fn cost_cha_digit_boundaries() {
4169        let mut buf = Vec::new();
4170        for col in [0u16, 8, 9, 98, 99, 998, 999, 9998, 9999, u16::MAX] {
4171            buf.clear();
4172            ansi::cha(&mut buf, col).unwrap();
4173            assert_eq!(
4174                buf.len(),
4175                cost_model::cha_cost(col),
4176                "CHA cost mismatch at col {col}"
4177            );
4178        }
4179    }
4180
4181    #[test]
4182    fn cost_cuf_digit_boundaries() {
4183        let mut buf = Vec::new();
4184        for n in [1u16, 2, 9, 10, 99, 100, 999, 1000, 9999, 10000, u16::MAX] {
4185            buf.clear();
4186            ansi::cuf(&mut buf, n).unwrap();
4187            assert_eq!(
4188                buf.len(),
4189                cost_model::cuf_cost(n),
4190                "CUF cost mismatch for n={n}"
4191            );
4192        }
4193    }
4194
4195    // --- RowPlan scratch reuse ---
4196
4197    #[test]
4198    fn plan_row_reuse_matches_plan_row() {
4199        let runs = [
4200            ChangeRun::new(5, 2, 4),
4201            ChangeRun::new(5, 8, 10),
4202            ChangeRun::new(5, 20, 25),
4203        ];
4204        let plan1 = cost_model::plan_row(&runs, Some(0), Some(5));
4205        let mut scratch = cost_model::RowPlanScratch::default();
4206        let plan2 = cost_model::plan_row_reuse(&runs, Some(0), Some(5), &mut scratch);
4207        assert_eq!(plan1, plan2);
4208    }
4209
4210    #[test]
4211    fn plan_row_reuse_single_run_matches_plan_row() {
4212        let runs = [ChangeRun::new(7, 18, 24)];
4213        let plan1 = cost_model::plan_row(&runs, Some(2), Some(7));
4214        let mut scratch = cost_model::RowPlanScratch::default();
4215        let plan2 = cost_model::plan_row_reuse(&runs, Some(2), Some(7), &mut scratch);
4216        assert_eq!(plan1, plan2);
4217        assert_eq!(
4218            plan2.total_cost(),
4219            cost_model::cheapest_move_cost(Some(2), Some(7), 18, 7) + runs[0].len()
4220        );
4221    }
4222
4223    #[test]
4224    fn emit_diff_runs_single_run_matches_planned_span_output() {
4225        let mut links = LinkRegistry::new();
4226        let link_id = links.register("https://example.com/single-run");
4227        let mut buffer = Buffer::new(16, 3);
4228
4229        for (offset, ch) in ['A', 'B', 'C', 'D'].into_iter().enumerate() {
4230            let x = 4 + offset as u16;
4231            let cell = Cell::from_char(ch)
4232                .with_fg(PackedRgba::rgb(10 + offset as u8, 20, 30))
4233                .with_bg(PackedRgba::rgb(1, 2 + offset as u8, 3))
4234                .with_attrs(CellAttrs::new(StyleFlags::BOLD, link_id));
4235            buffer.set_raw(x, 1, cell);
4236        }
4237
4238        let blank = Buffer::new(16, 3);
4239        let diff = BufferDiff::compute(&blank, &buffer);
4240        let runs = diff.runs();
4241        assert_eq!(runs.len(), 1, "fixture should produce one contiguous run");
4242        let run = runs[0];
4243
4244        let mut fast_path = test_presenter_with_hyperlinks();
4245        fast_path.prepare_runs(&diff);
4246        fast_path
4247            .emit_diff_runs(&buffer, None, Some(&links))
4248            .expect("single-run fast path should emit");
4249        fast_path
4250            .finish_frame()
4251            .expect("single-run fast path cleanup should succeed");
4252        let fast_output = fast_path.into_inner().expect("fast path output");
4253
4254        let planned_output = emit_spans_with_links_for_output(
4255            &buffer,
4256            &[cost_model::RowSpan {
4257                y: run.y,
4258                x0: run.x0,
4259                x1: run.x1,
4260            }],
4261            &links,
4262        );
4263
4264        assert_eq!(
4265            fast_output, planned_output,
4266            "single-run fast path must emit the same bytes as the planned one-span path"
4267        );
4268        assert!(
4269            fast_output
4270                .windows(b"https://example.com/single-run".len())
4271                .any(|window| window == b"https://example.com/single-run"),
4272            "linked single-run cells should still emit the hyperlink payload"
4273        );
4274    }
4275
4276    #[test]
4277    fn plan_row_reuse_across_different_sizes() {
4278        // Use scratch with a large row first, then a small row
4279        let mut scratch = cost_model::RowPlanScratch::default();
4280
4281        let large_runs: Vec<ChangeRun> = (0..20)
4282            .map(|i| ChangeRun::new(0, i * 4, i * 4 + 1))
4283            .collect();
4284        let plan_large = cost_model::plan_row_reuse(&large_runs, None, None, &mut scratch);
4285        assert!(!plan_large.spans().is_empty());
4286
4287        let small_runs = [ChangeRun::new(1, 5, 8)];
4288        let plan_small = cost_model::plan_row_reuse(&small_runs, None, None, &mut scratch);
4289        assert_eq!(plan_small.spans().len(), 1);
4290        assert_eq!(plan_small.spans()[0].x0, 5);
4291        assert_eq!(plan_small.spans()[0].x1, 8);
4292    }
4293
4294    // --- DP gap boundary (exactly 32 and 33 cells) ---
4295
4296    #[test]
4297    fn plan_row_gap_exactly_32_cells() {
4298        // Two runs with exactly 32-cell gap: run at 0-0 and 33-33
4299        // gap = 33 - 0 + 1 - 2 = 32 cells
4300        let runs = [ChangeRun::new(0, 0, 0), ChangeRun::new(0, 33, 33)];
4301        let plan = cost_model::plan_row(&runs, None, None);
4302        // 32-cell gap is at the break boundary; the DP may still consider merging
4303        // since the check is `gap_cells > 32` (strictly greater)
4304        // gap = 34 total - 2 changed = 32, which is NOT > 32, so merge is considered
4305        assert!(
4306            plan.spans().len() <= 2,
4307            "32-cell gap should still consider merge"
4308        );
4309    }
4310
4311    #[test]
4312    fn plan_row_gap_33_cells_stays_sparse() {
4313        // Two runs with 33-cell gap: run at 0-0 and 34-34
4314        // gap = 34 - 0 + 1 - 2 = 33 > 32, so merge is NOT considered
4315        let runs = [ChangeRun::new(0, 0, 0), ChangeRun::new(0, 34, 34)];
4316        let plan = cost_model::plan_row(&runs, None, None);
4317        assert_eq!(
4318            plan.spans().len(),
4319            2,
4320            "33-cell gap should stay sparse (gap > 32 breaks)"
4321        );
4322    }
4323
4324    // --- SmallVec spill: >4 separate spans ---
4325
4326    #[test]
4327    fn plan_row_many_sparse_spans() {
4328        // 6 runs with 34+ cell gaps between them (each gap > 32, no merging)
4329        let runs = [
4330            ChangeRun::new(0, 0, 0),
4331            ChangeRun::new(0, 40, 40),
4332            ChangeRun::new(0, 80, 80),
4333            ChangeRun::new(0, 120, 120),
4334            ChangeRun::new(0, 160, 160),
4335            ChangeRun::new(0, 200, 200),
4336        ];
4337        let plan = cost_model::plan_row(&runs, None, None);
4338        // All gaps are > 32, so no merging possible
4339        assert_eq!(plan.spans().len(), 6, "Should have 6 separate sparse spans");
4340    }
4341
4342    // --- CellStyle ---
4343
4344    #[test]
4345    fn cell_style_default_is_transparent_no_attrs() {
4346        let style = CellStyle::default();
4347        assert_eq!(style.fg, PackedRgba::TRANSPARENT);
4348        assert_eq!(style.bg, PackedRgba::TRANSPARENT);
4349        assert!(style.attrs.is_empty());
4350    }
4351
4352    #[test]
4353    fn cell_style_from_cell_captures_all() {
4354        let fg = PackedRgba::rgb(10, 20, 30);
4355        let bg = PackedRgba::rgb(40, 50, 60);
4356        let flags = StyleFlags::BOLD | StyleFlags::ITALIC;
4357        let cell = Cell::from_char('X')
4358            .with_fg(fg)
4359            .with_bg(bg)
4360            .with_attrs(CellAttrs::new(flags, 5));
4361        let style = CellStyle::from_cell(&cell);
4362        assert_eq!(style.fg, fg);
4363        assert_eq!(style.bg, bg);
4364        assert_eq!(style.attrs, flags);
4365    }
4366
4367    #[test]
4368    fn cell_style_eq_and_clone() {
4369        let a = CellStyle {
4370            fg: PackedRgba::rgb(1, 2, 3),
4371            bg: PackedRgba::TRANSPARENT,
4372            attrs: StyleFlags::DIM,
4373        };
4374        let b = a;
4375        assert_eq!(a, b);
4376    }
4377
4378    // --- SGR length estimation ---
4379
4380    #[test]
4381    fn sgr_flags_len_empty() {
4382        assert_eq!(Presenter::<Vec<u8>>::sgr_flags_len(StyleFlags::empty()), 0);
4383    }
4384
4385    #[test]
4386    fn sgr_flags_len_single() {
4387        // Single flag: "\x1b[1m" = 4 bytes → 3 + digits(code) + 0 separators
4388        let len = Presenter::<Vec<u8>>::sgr_flags_len(StyleFlags::BOLD);
4389        assert!(len > 0);
4390        // Verify by actually emitting
4391        let mut buf = Vec::new();
4392        ansi::sgr_flags(&mut buf, StyleFlags::BOLD).unwrap();
4393        assert_eq!(len as usize, buf.len());
4394    }
4395
4396    #[test]
4397    fn sgr_flags_len_multiple() {
4398        let flags = StyleFlags::BOLD | StyleFlags::ITALIC | StyleFlags::UNDERLINE;
4399        let len = Presenter::<Vec<u8>>::sgr_flags_len(flags);
4400        let mut buf = Vec::new();
4401        ansi::sgr_flags(&mut buf, flags).unwrap();
4402        assert_eq!(len as usize, buf.len());
4403    }
4404
4405    #[test]
4406    fn sgr_flags_off_len_empty() {
4407        assert_eq!(
4408            Presenter::<Vec<u8>>::sgr_flags_off_len(StyleFlags::empty()),
4409            0
4410        );
4411    }
4412
4413    #[test]
4414    fn sgr_truecolor_len_matches_actual() {
4415        let estimated = Presenter::<Vec<u8>>::sgr_truecolor_len(0, 0, 0);
4416        // "\x1b[38;2;0;0;0m" = 2(CSI) + "38;2;" + "0;0;0" + "m" but the estimate
4417        // is used for cost comparison, not exact output. Just check > 0.
4418        assert!(estimated > 0);
4419    }
4420
4421    #[test]
4422    fn sgr_truecolor_len_large_values() {
4423        let large_len = Presenter::<Vec<u8>>::sgr_truecolor_len(255, 255, 255);
4424        let small_len = Presenter::<Vec<u8>>::sgr_truecolor_len(0, 0, 0);
4425        // 255,255,255 has more digits than 0,0,0
4426        assert!(large_len > small_len);
4427    }
4428
4429    #[test]
4430    fn dec_len_u8_boundaries() {
4431        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(0), 1);
4432        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(9), 1);
4433        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(10), 2);
4434        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(99), 2);
4435        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(100), 3);
4436        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(255), 3);
4437    }
4438
4439    // --- Style delta corner cases ---
4440
4441    #[test]
4442    fn sgr_delta_all_attrs_removed_at_once() {
4443        let mut presenter = test_presenter();
4444        let all_flags = StyleFlags::BOLD
4445            | StyleFlags::DIM
4446            | StyleFlags::ITALIC
4447            | StyleFlags::UNDERLINE
4448            | StyleFlags::BLINK
4449            | StyleFlags::REVERSE
4450            | StyleFlags::STRIKETHROUGH;
4451        let old = CellStyle {
4452            fg: PackedRgba::rgb(100, 100, 100),
4453            bg: PackedRgba::TRANSPARENT,
4454            attrs: all_flags,
4455        };
4456        let new = CellStyle {
4457            fg: PackedRgba::rgb(100, 100, 100),
4458            bg: PackedRgba::TRANSPARENT,
4459            attrs: StyleFlags::empty(),
4460        };
4461
4462        presenter.current_style = Some(old);
4463        presenter.emit_style_delta(old, new).unwrap();
4464        let output = presenter.into_inner().unwrap();
4465
4466        // Should either use individual off codes or fall back to full reset
4467        // Either way, output should be non-empty
4468        assert!(!output.is_empty());
4469    }
4470
4471    #[test]
4472    fn sgr_delta_fg_to_transparent() {
4473        let mut presenter = test_presenter();
4474        let old = CellStyle {
4475            fg: PackedRgba::rgb(200, 100, 50),
4476            bg: PackedRgba::TRANSPARENT,
4477            attrs: StyleFlags::empty(),
4478        };
4479        let new = CellStyle {
4480            fg: PackedRgba::TRANSPARENT,
4481            bg: PackedRgba::TRANSPARENT,
4482            attrs: StyleFlags::empty(),
4483        };
4484
4485        presenter.current_style = Some(old);
4486        presenter.emit_style_delta(old, new).unwrap();
4487        let output = presenter.into_inner().unwrap();
4488        let output_str = String::from_utf8_lossy(&output);
4489
4490        // When going to TRANSPARENT fg, the delta should emit the default fg code
4491        // or reset. Either way, output should be non-empty.
4492        assert!(!output.is_empty(), "Should emit fg removal: {output_str:?}");
4493    }
4494
4495    #[test]
4496    fn sgr_delta_bg_to_transparent() {
4497        let mut presenter = test_presenter();
4498        let old = CellStyle {
4499            fg: PackedRgba::TRANSPARENT,
4500            bg: PackedRgba::rgb(30, 60, 90),
4501            attrs: StyleFlags::empty(),
4502        };
4503        let new = CellStyle {
4504            fg: PackedRgba::TRANSPARENT,
4505            bg: PackedRgba::TRANSPARENT,
4506            attrs: StyleFlags::empty(),
4507        };
4508
4509        presenter.current_style = Some(old);
4510        presenter.emit_style_delta(old, new).unwrap();
4511        let output = presenter.into_inner().unwrap();
4512        assert!(!output.is_empty(), "Should emit bg removal");
4513    }
4514
4515    #[test]
4516    fn sgr_delta_dim_removed_bold_stays() {
4517        // Reverse of the bold-dim collateral test: removing DIM while BOLD stays.
4518        // DIM off (code 22) also disables BOLD. If BOLD should remain,
4519        // the delta engine must re-enable BOLD.
4520        let mut presenter = test_presenter();
4521        let mut buffer = Buffer::new(3, 1);
4522
4523        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::DIM, 0);
4524        let attrs2 = CellAttrs::new(StyleFlags::BOLD, 0);
4525        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
4526        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));
4527
4528        let old = Buffer::new(3, 1);
4529        let diff = BufferDiff::compute(&old, &buffer);
4530
4531        presenter.present(&buffer, &diff).unwrap();
4532        let output = get_output(presenter);
4533        let output_str = String::from_utf8_lossy(&output);
4534
4535        // Should contain dim-off (22) and then bold re-enable (1)
4536        assert!(
4537            output_str.contains("\x1b[22m"),
4538            "Expected dim-off (22) in: {output_str:?}"
4539        );
4540        assert!(
4541            output_str.contains("\x1b[1m"),
4542            "Expected bold re-enable (1) in: {output_str:?}"
4543        );
4544    }
4545
4546    #[test]
4547    fn sgr_delta_fallback_to_full_reset_when_cheaper() {
4548        // Many attrs removed + colors changed → delta is expensive, full reset is cheaper
4549        let mut presenter = test_presenter();
4550        let old = CellStyle {
4551            fg: PackedRgba::rgb(10, 20, 30),
4552            bg: PackedRgba::rgb(40, 50, 60),
4553            attrs: StyleFlags::BOLD
4554                | StyleFlags::DIM
4555                | StyleFlags::ITALIC
4556                | StyleFlags::UNDERLINE
4557                | StyleFlags::STRIKETHROUGH,
4558        };
4559        let new = CellStyle {
4560            fg: PackedRgba::TRANSPARENT,
4561            bg: PackedRgba::TRANSPARENT,
4562            attrs: StyleFlags::empty(),
4563        };
4564
4565        presenter.current_style = Some(old);
4566        presenter.emit_style_delta(old, new).unwrap();
4567        let output = presenter.into_inner().unwrap();
4568        let output_str = String::from_utf8_lossy(&output);
4569
4570        // With everything removed and going to default, full reset ("\x1b[0m") is cheapest
4571        assert!(
4572            output_str.contains("\x1b[0m"),
4573            "Expected full reset fallback: {output_str:?}"
4574        );
4575    }
4576
4577    // --- Content emission edge cases ---
4578
4579    #[test]
4580    fn emit_cell_control_char_replaced_with_fffd() {
4581        let mut presenter = test_presenter();
4582        presenter.cursor_x = Some(0);
4583        presenter.cursor_y = Some(0);
4584
4585        // Control character '\x01' has width 0, not empty, not continuation.
4586        // The zero-width-content path replaces it with U+FFFD.
4587        let cell = Cell::from_char('\x01');
4588        presenter.emit_cell(0, &cell, None, None).unwrap();
4589        let output = presenter.into_inner().unwrap();
4590        let output_str = String::from_utf8_lossy(&output);
4591
4592        // Should emit U+FFFD (replacement character), not the raw control char
4593        assert!(
4594            output_str.contains('\u{FFFD}'),
4595            "Control char (width 0) should be replaced with U+FFFD, got: {output:?}"
4596        );
4597        assert!(
4598            !output.contains(&0x01),
4599            "Raw control char should not appear"
4600        );
4601    }
4602
4603    #[test]
4604    fn emit_content_empty_cell_emits_space() {
4605        let mut presenter = test_presenter();
4606        presenter.cursor_x = Some(0);
4607        presenter.cursor_y = Some(0);
4608
4609        let cell = Cell::default();
4610        assert!(cell.is_empty());
4611        presenter.emit_cell(0, &cell, None, None).unwrap();
4612        let output = presenter.into_inner().unwrap();
4613        assert!(output.contains(&b' '), "Empty cell should emit space");
4614    }
4615
4616    #[test]
4617    fn emit_content_ascii_char_emits_single_byte() {
4618        let mut presenter = test_presenter();
4619        presenter
4620            .emit_content(PreparedContent::Char('A'), 1, None)
4621            .unwrap();
4622        let output = presenter.into_inner().unwrap();
4623        assert_eq!(output, b"A");
4624    }
4625
4626    #[test]
4627    fn emit_content_ascii_control_sanitizes_to_space() {
4628        let mut presenter = test_presenter();
4629        presenter
4630            .emit_content(PreparedContent::Char('\n'), 1, None)
4631            .unwrap();
4632        let output = presenter.into_inner().unwrap();
4633        assert_eq!(output, b" ");
4634    }
4635
4636    #[test]
4637    fn prepared_content_ascii_widths_match_char_width_contract() {
4638        for ch in ['A', ' ', '\n', '\r', '\x1f', '\x7f'] {
4639            let cell = Cell::from_char(ch);
4640            let (prepared, width) = PreparedContent::from_cell(&cell);
4641            assert_eq!(prepared, PreparedContent::Char(ch));
4642            assert_eq!(width, char_width(ch), "width mismatch for {ch:?}");
4643        }
4644    }
4645
4646    #[test]
4647    fn prepared_content_tab_uses_canonicalized_space() {
4648        let cell = Cell::from_char('\t');
4649        let (prepared, width) = PreparedContent::from_cell(&cell);
4650        assert_eq!(prepared, PreparedContent::Char(' '));
4651        assert_eq!(width, 1);
4652    }
4653
4654    #[test]
4655    fn prepared_content_nul_uses_empty_cell_representation() {
4656        let cell = Cell::from_char('\0');
4657        let (prepared, width) = PreparedContent::from_cell(&cell);
4658        assert_eq!(prepared, PreparedContent::Empty);
4659        assert_eq!(width, 0);
4660    }
4661
4662    #[test]
4663    fn emit_content_grapheme_sanitizes_escape_sequences() {
4664        let mut presenter = test_presenter();
4665        presenter.cursor_x = Some(0);
4666        presenter.cursor_y = Some(0);
4667
4668        let mut pool = GraphemePool::new();
4669        let gid = pool.intern("A\x1b[31mB\x1b[0m", 2);
4670        let cell = Cell::new(CellContent::from_grapheme(gid));
4671        presenter.emit_cell(0, &cell, Some(&pool), None).unwrap();
4672
4673        let output = presenter.into_inner().unwrap();
4674        let output_str = String::from_utf8_lossy(&output);
4675        assert!(
4676            output_str.contains("AB"),
4677            "sanitized grapheme should preserve visible payload"
4678        );
4679        assert!(
4680            !output_str.contains("\x1b[31m"),
4681            "raw escape sequence must not be emitted"
4682        );
4683    }
4684
4685    #[test]
4686    fn emit_content_grapheme_width_mismatch_uses_placeholders() {
4687        let mut presenter = test_presenter();
4688        let mut pool = GraphemePool::new();
4689        let gid = pool.intern("A\x07", 2);
4690
4691        presenter
4692            .emit_content(PreparedContent::Grapheme(gid), 2, Some(&pool))
4693            .unwrap();
4694
4695        let output = presenter.into_inner().unwrap();
4696        assert_eq!(output, b"??");
4697    }
4698
4699    #[test]
4700    fn wide_grapheme_tail_repair_does_not_blank_unrelated_following_cells() {
4701        let mut presenter = test_presenter();
4702        let mut pool = GraphemePool::new();
4703        let gid = pool.intern("XYZ", 3);
4704        let mut buffer = Buffer::new(8, 1);
4705
4706        buffer.set_raw(0, 0, Cell::new(CellContent::from_grapheme(gid)));
4707        buffer.set_raw(1, 0, Cell::from_char('a'));
4708        buffer.set_raw(2, 0, Cell::from_char('b'));
4709        buffer.set_raw(3, 0, Cell::from_char('c'));
4710
4711        let old = Buffer::new(8, 1);
4712        let diff = BufferDiff::compute(&old, &buffer);
4713
4714        presenter
4715            .present_with_pool(&buffer, &diff, Some(&pool), None)
4716            .unwrap();
4717
4718        let output = presenter.into_inner().unwrap();
4719        let output_str = String::from_utf8_lossy(&output);
4720        let visible = sanitize(output_str.as_ref());
4721
4722        assert!(
4723            visible.contains("XYZabc"),
4724            "width-3 grapheme repair must not erase following cells: {:?}",
4725            visible
4726        );
4727    }
4728
4729    // --- Continuation cell cursor_x variants ---
4730
4731    #[test]
4732    fn continuation_cell_cursor_x_none() {
4733        let mut presenter = test_presenter();
4734        // cursor_x = None -> defensive path, clears orphan continuation.
4735        presenter.cursor_x = None;
4736        presenter.cursor_y = Some(0);
4737
4738        let cell = Cell::CONTINUATION;
4739        presenter.emit_cell(5, &cell, None, None).unwrap();
4740        let output = presenter.into_inner().unwrap();
4741
4742        // Should emit a clearing space.
4743        assert!(
4744            output.contains(&b' '),
4745            "Should emit a space for continuation with unknown cursor_x"
4746        );
4747    }
4748
4749    #[test]
4750    fn continuation_cell_cursor_already_past() {
4751        let mut presenter = test_presenter();
4752        // cursor_x > cell x → cursor already advanced past, skip
4753        presenter.cursor_x = Some(10);
4754        presenter.cursor_y = Some(0);
4755
4756        let cell = Cell::CONTINUATION;
4757        presenter.emit_cell(5, &cell, None, None).unwrap();
4758        let output = presenter.into_inner().unwrap();
4759
4760        // Should produce no output (cursor already past)
4761        assert!(
4762            output.is_empty(),
4763            "Should skip continuation when cursor is past it"
4764        );
4765    }
4766
4767    // --- clear_line ---
4768
4769    #[test]
4770    fn clear_line_positions_cursor_and_erases() {
4771        let mut presenter = test_presenter();
4772        presenter.clear_line(5).unwrap();
4773        let output = get_output(presenter);
4774        let output_str = String::from_utf8_lossy(&output);
4775
4776        // Should contain CUP to row 5 col 0 and erase line
4777        assert!(
4778            output_str.contains("\x1b[2K"),
4779            "Should contain erase line sequence"
4780        );
4781    }
4782
4783    // --- into_inner ---
4784
4785    #[test]
4786    fn into_inner_returns_accumulated_output() {
4787        let mut presenter = test_presenter();
4788        presenter.position_cursor(0, 0).unwrap();
4789        let inner = presenter.into_inner().unwrap();
4790        assert!(!inner.is_empty(), "into_inner should return buffered data");
4791    }
4792
4793    // --- move_cursor_optimal edge cases ---
4794
4795    #[test]
4796    fn move_cursor_optimal_same_row_forward_large() {
4797        let mut presenter = test_presenter();
4798        presenter.cursor_x = Some(0);
4799        presenter.cursor_y = Some(0);
4800
4801        // Forward by 100 columns. CUF(100) vs CHA(100) vs CUP(0,100)
4802        presenter.move_cursor_optimal(100, 0).unwrap();
4803        let output = presenter.into_inner().unwrap();
4804
4805        // Verify the output picks the cheapest move
4806        let cuf = cost_model::cuf_cost(100);
4807        let cha = cost_model::cha_cost(100);
4808        let cup = cost_model::cup_cost(0, 100);
4809        let cheapest = cuf.min(cha).min(cup);
4810        assert_eq!(output.len(), cheapest, "Should pick cheapest cursor move");
4811    }
4812
4813    #[test]
4814    fn move_cursor_optimal_same_row_backward_to_zero() {
4815        let mut presenter = test_presenter();
4816        presenter.cursor_x = Some(50);
4817        presenter.cursor_y = Some(0);
4818
4819        presenter.move_cursor_optimal(0, 0).unwrap();
4820        let output = presenter.into_inner().unwrap();
4821
4822        // CHA(0) → "\x1b[1G" = 4 bytes, CUP(0,0) = "\x1b[1;1H" = 6 bytes
4823        // CHA should win
4824        let mut expected = Vec::new();
4825        ansi::cha(&mut expected, 0).unwrap();
4826        assert_eq!(output, expected, "Should use CHA for backward to col 0");
4827    }
4828
4829    #[test]
4830    fn move_cursor_optimal_unknown_cursor_uses_cup() {
4831        let mut presenter = test_presenter();
4832        // cursor_x and cursor_y are None
4833        presenter.move_cursor_optimal(10, 5).unwrap();
4834        let output = presenter.into_inner().unwrap();
4835        let mut expected = Vec::new();
4836        ansi::cup(&mut expected, 5, 10).unwrap();
4837        assert_eq!(output, expected, "Should use CUP when cursor is unknown");
4838    }
4839
4840    // --- Present with sync: verify wrap order ---
4841
4842    #[test]
4843    fn sync_wrap_order_begin_content_reset_end() {
4844        let mut presenter = test_presenter_with_sync();
4845        let mut buffer = Buffer::new(3, 1);
4846        buffer.set_raw(0, 0, Cell::from_char('Z'));
4847
4848        let old = Buffer::new(3, 1);
4849        let diff = BufferDiff::compute(&old, &buffer);
4850
4851        presenter.present(&buffer, &diff).unwrap();
4852        let output = get_output(presenter);
4853
4854        let sync_begin_pos = output
4855            .windows(ansi::SYNC_BEGIN.len())
4856            .position(|w| w == ansi::SYNC_BEGIN)
4857            .expect("sync begin missing");
4858        let z_pos = output
4859            .iter()
4860            .position(|&b| b == b'Z')
4861            .expect("character Z missing");
4862        let reset_pos = output
4863            .windows(b"\x1b[0m".len())
4864            .rposition(|w| w == b"\x1b[0m")
4865            .expect("SGR reset missing");
4866        let sync_end_pos = output
4867            .windows(ansi::SYNC_END.len())
4868            .rposition(|w| w == ansi::SYNC_END)
4869            .expect("sync end missing");
4870
4871        assert!(sync_begin_pos < z_pos, "sync begin before content");
4872        assert!(z_pos < reset_pos, "content before reset");
4873        assert!(reset_pos < sync_end_pos, "reset before sync end");
4874    }
4875
4876    // --- Multi-frame style state ---
4877
4878    #[test]
4879    fn style_none_after_each_frame() {
4880        let mut presenter = test_presenter();
4881        let fg = PackedRgba::rgb(255, 128, 64);
4882
4883        for _ in 0..5 {
4884            let mut buffer = Buffer::new(3, 1);
4885            buffer.set_raw(0, 0, Cell::from_char('X').with_fg(fg));
4886            let old = Buffer::new(3, 1);
4887            let diff = BufferDiff::compute(&old, &buffer);
4888            presenter.present(&buffer, &diff).unwrap();
4889
4890            // After each present(), current_style should be None (reset at frame end)
4891            assert!(
4892                presenter.current_style.is_none(),
4893                "Style should be None after frame end"
4894            );
4895            assert!(
4896                presenter.current_link.is_none(),
4897                "Link should be None after frame end"
4898            );
4899        }
4900    }
4901
4902    // --- Link state after present with open link ---
4903
4904    #[test]
4905    fn link_closed_at_frame_end_even_if_all_cells_linked() {
4906        let mut presenter = test_presenter();
4907        let mut buffer = Buffer::new(3, 1);
4908        let mut links = LinkRegistry::new();
4909        let link_id = links.register("https://all-linked.test");
4910
4911        // All cells have the same link
4912        for x in 0..3 {
4913            buffer.set_raw(
4914                x,
4915                0,
4916                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
4917            );
4918        }
4919
4920        let old = Buffer::new(3, 1);
4921        let diff = BufferDiff::compute(&old, &buffer);
4922        presenter
4923            .present_with_pool(&buffer, &diff, None, Some(&links))
4924            .unwrap();
4925
4926        // After present, current_link must be None (closed at frame end)
4927        assert!(
4928            presenter.current_link.is_none(),
4929            "Link must be closed at frame end"
4930        );
4931    }
4932
4933    // --- PresentStats ---
4934
4935    #[test]
4936    fn present_stats_empty_diff() {
4937        let mut presenter = test_presenter();
4938        let buffer = Buffer::new(10, 10);
4939        let diff = BufferDiff::new();
4940        let stats = presenter.present(&buffer, &diff).unwrap();
4941
4942        assert_eq!(stats.cells_changed, 0);
4943        assert_eq!(stats.run_count, 0);
4944        // bytes_emitted includes the SGR reset
4945        assert!(stats.bytes_emitted > 0);
4946    }
4947
4948    #[test]
4949    fn present_stats_full_row() {
4950        let mut presenter = test_presenter();
4951        let mut buffer = Buffer::new(10, 1);
4952        for x in 0..10 {
4953            buffer.set_raw(x, 0, Cell::from_char('A'));
4954        }
4955        let old = Buffer::new(10, 1);
4956        let diff = BufferDiff::compute(&old, &buffer);
4957        let stats = presenter.present(&buffer, &diff).unwrap();
4958
4959        assert_eq!(stats.cells_changed, 10);
4960        assert!(stats.run_count >= 1);
4961        assert!(stats.bytes_emitted > 10, "Should include ANSI overhead");
4962    }
4963
4964    // --- Capabilities accessor ---
4965
4966    #[test]
4967    fn capabilities_accessor() {
4968        let mut caps = TerminalCapabilities::basic();
4969        caps.sync_output = true;
4970        let presenter = Presenter::new(Vec::<u8>::new(), caps);
4971        assert!(presenter.capabilities().sync_output);
4972    }
4973
4974    // --- Flush ---
4975
4976    #[test]
4977    fn flush_succeeds_on_empty_presenter() {
4978        let mut presenter = test_presenter();
4979        presenter.flush().unwrap();
4980        let output = get_output(presenter);
4981        assert!(output.is_empty());
4982    }
4983
4984    // --- RowPlan total_cost ---
4985
4986    #[test]
4987    fn row_plan_total_cost_matches_dp() {
4988        let runs = [ChangeRun::new(3, 5, 10), ChangeRun::new(3, 15, 20)];
4989        let plan = cost_model::plan_row(&runs, None, None);
4990        assert!(plan.total_cost() > 0);
4991        // The total cost includes move costs + cell costs
4992        // Just verify it's consistent (non-zero) and accessible
4993    }
4994
4995    // --- Style delta: same attrs, only colors change (hot path) ---
4996
4997    #[test]
4998    fn sgr_delta_hot_path_only_fg_change() {
4999        let mut presenter = test_presenter();
5000        let old = CellStyle {
5001            fg: PackedRgba::rgb(255, 0, 0),
5002            bg: PackedRgba::rgb(0, 0, 0),
5003            attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
5004        };
5005        let new = CellStyle {
5006            fg: PackedRgba::rgb(0, 255, 0),
5007            bg: PackedRgba::rgb(0, 0, 0),
5008            attrs: StyleFlags::BOLD | StyleFlags::ITALIC, // same attrs
5009        };
5010
5011        presenter.current_style = Some(old);
5012        presenter.emit_style_delta(old, new).unwrap();
5013        let output = presenter.into_inner().unwrap();
5014        let output_str = String::from_utf8_lossy(&output);
5015
5016        // Only fg should change, no reset
5017        assert!(output_str.contains("38;2;0;255;0"), "Should emit new fg");
5018        assert!(
5019            !output_str.contains("\x1b[0m"),
5020            "No reset needed for color-only change"
5021        );
5022        // Should NOT re-emit attrs
5023        assert!(
5024            !output_str.contains("\x1b[1m"),
5025            "Bold should not be re-emitted"
5026        );
5027    }
5028
5029    #[test]
5030    fn sgr_delta_hot_path_both_colors_change() {
5031        let mut presenter = test_presenter();
5032        let old = CellStyle {
5033            fg: PackedRgba::rgb(1, 2, 3),
5034            bg: PackedRgba::rgb(4, 5, 6),
5035            attrs: StyleFlags::UNDERLINE,
5036        };
5037        let new = CellStyle {
5038            fg: PackedRgba::rgb(7, 8, 9),
5039            bg: PackedRgba::rgb(10, 11, 12),
5040            attrs: StyleFlags::UNDERLINE, // same
5041        };
5042
5043        presenter.current_style = Some(old);
5044        presenter.emit_style_delta(old, new).unwrap();
5045        let output = presenter.into_inner().unwrap();
5046        let output_str = String::from_utf8_lossy(&output);
5047
5048        assert!(output_str.contains("38;2;7;8;9"), "Should emit new fg");
5049        assert!(output_str.contains("48;2;10;11;12"), "Should emit new bg");
5050        assert!(!output_str.contains("\x1b[0m"), "No reset for color-only");
5051    }
5052
5053    // --- Style full apply ---
5054
5055    #[test]
5056    fn emit_style_full_default_is_just_reset() {
5057        let mut presenter = test_presenter();
5058        let default_style = CellStyle::default();
5059        presenter.emit_style_full(default_style).unwrap();
5060        let output = presenter.into_inner().unwrap();
5061
5062        // Default style (transparent fg/bg, no attrs) should just be reset
5063        assert_eq!(output, b"\x1b[0m");
5064    }
5065
5066    #[test]
5067    fn emit_style_full_with_all_properties() {
5068        let mut presenter = test_presenter();
5069        let style = CellStyle {
5070            fg: PackedRgba::rgb(10, 20, 30),
5071            bg: PackedRgba::rgb(40, 50, 60),
5072            attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
5073        };
5074        presenter.emit_style_full(style).unwrap();
5075        let output = presenter.into_inner().unwrap();
5076        let output_str = String::from_utf8_lossy(&output);
5077
5078        // Should have reset + fg + bg + attrs
5079        assert!(output_str.contains("\x1b[0m"), "Should start with reset");
5080        assert!(output_str.contains("38;2;10;20;30"), "Should have fg");
5081        assert!(output_str.contains("48;2;40;50;60"), "Should have bg");
5082    }
5083
5084    // --- Multiple rows with different strategies ---
5085
5086    #[test]
5087    fn present_multiple_rows_different_strategies() {
5088        let mut presenter = test_presenter();
5089        let mut buffer = Buffer::new(80, 5);
5090
5091        // Row 0: dense changes (should merge)
5092        for x in (0..20).step_by(2) {
5093            buffer.set_raw(x, 0, Cell::from_char('D'));
5094        }
5095        // Row 2: sparse changes (large gap, should stay sparse)
5096        buffer.set_raw(0, 2, Cell::from_char('L'));
5097        buffer.set_raw(79, 2, Cell::from_char('R'));
5098        // Row 4: single cell
5099        buffer.set_raw(40, 4, Cell::from_char('M'));
5100
5101        let old = Buffer::new(80, 5);
5102        let diff = BufferDiff::compute(&old, &buffer);
5103        presenter.present(&buffer, &diff).unwrap();
5104        let output = get_output(presenter);
5105        let output_str = String::from_utf8_lossy(&output);
5106
5107        assert!(output_str.contains('D'));
5108        assert!(output_str.contains('L'));
5109        assert!(output_str.contains('R'));
5110        assert!(output_str.contains('M'));
5111    }
5112
5113    #[test]
5114    fn zero_width_chars_replaced_with_placeholder() {
5115        let mut presenter = test_presenter();
5116        let mut buffer = Buffer::new(5, 1);
5117
5118        // U+0301 is COMBINING ACUTE ACCENT (width 0).
5119        // It is not empty, not continuation, not grapheme (unless pooled).
5120        // Storing it directly as a char means it's a standalone cell content.
5121        let zw_char = '\u{0301}';
5122
5123        // Ensure our assumption about width is correct for this environment
5124        assert_eq!(Cell::from_char(zw_char).content.width(), 0);
5125
5126        buffer.set_raw(0, 0, Cell::from_char(zw_char));
5127        buffer.set_raw(1, 0, Cell::from_char('A'));
5128
5129        let old = Buffer::new(5, 1);
5130        let diff = BufferDiff::compute(&old, &buffer);
5131
5132        presenter.present(&buffer, &diff).unwrap();
5133        let output = get_output(presenter);
5134        let output_str = String::from_utf8_lossy(&output);
5135
5136        // Should contain U+FFFD (Replacement Character)
5137        assert!(
5138            output_str.contains("\u{FFFD}"),
5139            "Expected replacement character for zero-width content, got: {:?}",
5140            output_str
5141        );
5142
5143        // Should NOT contain the raw combining mark
5144        assert!(
5145            !output_str.contains(zw_char),
5146            "Should not contain raw zero-width char"
5147        );
5148
5149        // Should contain 'A' (verify cursor sync didn't swallow it)
5150        assert!(
5151            output_str.contains('A'),
5152            "Should contain subsequent character 'A'"
5153        );
5154    }
5155}
5156
5157#[cfg(test)]
5158mod proptests {
5159    use super::*;
5160    use crate::cell::{Cell, PackedRgba};
5161    use crate::diff::BufferDiff;
5162    use crate::terminal_model::TerminalModel;
5163    use proptest::prelude::*;
5164
5165    /// Create a presenter for testing.
5166    fn test_presenter() -> Presenter<Vec<u8>> {
5167        let caps = TerminalCapabilities::basic();
5168        Presenter::new(Vec::new(), caps)
5169    }
5170
5171    proptest! {
5172        /// Property: Presenter output, when applied to terminal model, produces
5173        /// the correct characters for changed cells.
5174        #[test]
5175        fn presenter_roundtrip_characters(
5176            width in 5u16..40,
5177            height in 3u16..20,
5178            num_chars in 1usize..50, // At least 1 char to have meaningful diff
5179        ) {
5180            let mut buffer = Buffer::new(width, height);
5181            let mut changed_positions = std::collections::HashSet::new();
5182
5183            // Fill some cells with ASCII chars
5184            for i in 0..num_chars {
5185                let x = (i * 7 + 3) as u16 % width;
5186                let y = (i * 11 + 5) as u16 % height;
5187                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
5188                buffer.set_raw(x, y, Cell::from_char(ch));
5189                changed_positions.insert((x, y));
5190            }
5191
5192            // Present full buffer
5193            let mut presenter = test_presenter();
5194            let old = Buffer::new(width, height);
5195            let diff = BufferDiff::compute(&old, &buffer);
5196            presenter.present(&buffer, &diff).unwrap();
5197            let output = presenter.into_inner().unwrap();
5198
5199            // Apply to terminal model
5200            let mut model = TerminalModel::new(width as usize, height as usize);
5201            model.process(&output);
5202
5203            // Verify ONLY changed characters match (model may have different default)
5204            for &(x, y) in &changed_positions {
5205                let buf_cell = buffer.get_unchecked(x, y);
5206                let expected_ch = buf_cell.content.as_char().unwrap_or(' ');
5207                let mut expected_buf = [0u8; 4];
5208                let expected_str = expected_ch.encode_utf8(&mut expected_buf);
5209
5210                if let Some(model_cell) = model.cell(x as usize, y as usize) {
5211                    prop_assert_eq!(
5212                        model_cell.text.as_str(),
5213                        expected_str,
5214                        "Character mismatch at ({}, {})", x, y
5215                    );
5216                }
5217            }
5218        }
5219
5220        /// Property: After complete frame presentation, SGR is reset.
5221        #[test]
5222        fn style_reset_after_present(
5223            width in 5u16..30,
5224            height in 3u16..15,
5225            num_styled in 1usize..20,
5226        ) {
5227            let mut buffer = Buffer::new(width, height);
5228
5229            // Add some styled cells
5230            for i in 0..num_styled {
5231                let x = (i * 7) as u16 % width;
5232                let y = (i * 11) as u16 % height;
5233                let fg = PackedRgba::rgb(
5234                    ((i * 31) % 256) as u8,
5235                    ((i * 47) % 256) as u8,
5236                    ((i * 71) % 256) as u8,
5237                );
5238                buffer.set_raw(x, y, Cell::from_char('X').with_fg(fg));
5239            }
5240
5241            // Present
5242            let mut presenter = test_presenter();
5243            let old = Buffer::new(width, height);
5244            let diff = BufferDiff::compute(&old, &buffer);
5245            presenter.present(&buffer, &diff).unwrap();
5246            let output = presenter.into_inner().unwrap();
5247            let output_str = String::from_utf8_lossy(&output);
5248
5249            // Output should end with SGR reset sequence
5250            prop_assert!(
5251                output_str.contains("\x1b[0m"),
5252                "Output should contain SGR reset"
5253            );
5254        }
5255
5256        /// Property: Presenter handles empty diff correctly.
5257        #[test]
5258        fn empty_diff_minimal_output(
5259            width in 5u16..50,
5260            height in 3u16..25,
5261        ) {
5262            let buffer = Buffer::new(width, height);
5263            let diff = BufferDiff::new(); // Empty diff
5264
5265            let mut presenter = test_presenter();
5266            presenter.present(&buffer, &diff).unwrap();
5267            let output = presenter.into_inner().unwrap();
5268
5269            // Output should only be SGR reset (or very minimal)
5270            // No cursor moves or cell content for empty diff
5271            prop_assert!(output.len() < 50, "Empty diff should have minimal output");
5272        }
5273
5274        /// Property: Full buffer change produces diff with all cells.
5275        ///
5276        /// When every cell differs, the diff should contain exactly
5277        /// width * height changes.
5278        #[test]
5279        fn diff_size_bounds(
5280            width in 5u16..30,
5281            height in 3u16..15,
5282        ) {
5283            // Full change buffer
5284            let old = Buffer::new(width, height);
5285            let mut new = Buffer::new(width, height);
5286
5287            for y in 0..height {
5288                for x in 0..width {
5289                    new.set_raw(x, y, Cell::from_char('X'));
5290                }
5291            }
5292
5293            let diff = BufferDiff::compute(&old, &new);
5294
5295            // Diff should capture all cells
5296            prop_assert_eq!(
5297                diff.len(),
5298                (width as usize) * (height as usize),
5299                "Full change should have all cells in diff"
5300            );
5301        }
5302
5303        /// Property: Presenter cursor state is consistent after operations.
5304        #[test]
5305        fn presenter_cursor_consistency(
5306            width in 10u16..40,
5307            height in 5u16..20,
5308            num_runs in 1usize..10,
5309        ) {
5310            let mut buffer = Buffer::new(width, height);
5311
5312            // Create some runs of changes
5313            for i in 0..num_runs {
5314                let start_x = (i * 5) as u16 % (width - 5);
5315                let y = i as u16 % height;
5316                for x in start_x..(start_x + 3) {
5317                    buffer.set_raw(x, y, Cell::from_char('A'));
5318                }
5319            }
5320
5321            // Multiple presents should work correctly
5322            let mut presenter = test_presenter();
5323            let old = Buffer::new(width, height);
5324
5325            for _ in 0..3 {
5326                let diff = BufferDiff::compute(&old, &buffer);
5327                presenter.present(&buffer, &diff).unwrap();
5328            }
5329
5330            // Should not panic and produce valid output
5331            let output = presenter.into_inner().unwrap();
5332            prop_assert!(!output.is_empty(), "Should produce some output");
5333        }
5334
5335        /// Property (bd-4kq0.2.1): SGR delta produces identical visual styling
5336        /// as reset+apply for random style transitions. Verified via terminal
5337        /// model roundtrip.
5338        #[test]
5339        fn sgr_delta_transition_equivalence(
5340            width in 5u16..20,
5341            height in 3u16..10,
5342            num_styled in 2usize..15,
5343        ) {
5344            let mut buffer = Buffer::new(width, height);
5345            // Track final character at each position (later writes overwrite earlier)
5346            let mut expected: std::collections::HashMap<(u16, u16), char> =
5347                std::collections::HashMap::new();
5348
5349            // Create cells with varying styles to exercise delta engine
5350            for i in 0..num_styled {
5351                let x = (i * 3 + 1) as u16 % width;
5352                let y = (i * 5 + 2) as u16 % height;
5353                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
5354                let fg = PackedRgba::rgb(
5355                    ((i * 73) % 256) as u8,
5356                    ((i * 137) % 256) as u8,
5357                    ((i * 41) % 256) as u8,
5358                );
5359                let bg = if i % 3 == 0 {
5360                    PackedRgba::rgb(
5361                        ((i * 29) % 256) as u8,
5362                        ((i * 53) % 256) as u8,
5363                        ((i * 97) % 256) as u8,
5364                    )
5365                } else {
5366                    PackedRgba::TRANSPARENT
5367                };
5368                let flags_bits = ((i * 37) % 256) as u8;
5369                let flags = StyleFlags::from_bits_truncate(flags_bits);
5370                let cell = Cell::from_char(ch)
5371                    .with_fg(fg)
5372                    .with_bg(bg)
5373                    .with_attrs(CellAttrs::new(flags, 0));
5374                buffer.set_raw(x, y, cell);
5375                expected.insert((x, y), ch);
5376            }
5377
5378            // Present with delta engine
5379            let mut presenter = test_presenter();
5380            let old = Buffer::new(width, height);
5381            let diff = BufferDiff::compute(&old, &buffer);
5382            presenter.present(&buffer, &diff).unwrap();
5383            let output = presenter.into_inner().unwrap();
5384
5385            // Apply to terminal model and verify characters
5386            let mut model = TerminalModel::new(width as usize, height as usize);
5387            model.process(&output);
5388
5389            for (&(x, y), &ch) in &expected {
5390                let mut buf = [0u8; 4];
5391                let expected_str = ch.encode_utf8(&mut buf);
5392
5393                if let Some(model_cell) = model.cell(x as usize, y as usize) {
5394                    prop_assert_eq!(
5395                        model_cell.text.as_str(),
5396                        expected_str,
5397                        "Character mismatch at ({}, {}) with delta engine", x, y
5398                    );
5399                }
5400            }
5401        }
5402
5403        /// Property (bd-4kq0.2.2): DP cost model produces correct output
5404        /// regardless of which row strategy is chosen (sparse vs merged).
5405        /// Verified via terminal model roundtrip with scattered runs.
5406        #[test]
5407        fn dp_emit_equivalence(
5408            width in 20u16..60,
5409            height in 5u16..15,
5410            num_changes in 5usize..30,
5411        ) {
5412            let mut buffer = Buffer::new(width, height);
5413            let mut expected: std::collections::HashMap<(u16, u16), char> =
5414                std::collections::HashMap::new();
5415
5416            // Create scattered changes that will trigger both sparse and merged strategies
5417            for i in 0..num_changes {
5418                let x = (i * 7 + 3) as u16 % width;
5419                let y = (i * 3 + 1) as u16 % height;
5420                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
5421                buffer.set_raw(x, y, Cell::from_char(ch));
5422                expected.insert((x, y), ch);
5423            }
5424
5425            // Present with DP cost model
5426            let mut presenter = test_presenter();
5427            let old = Buffer::new(width, height);
5428            let diff = BufferDiff::compute(&old, &buffer);
5429            presenter.present(&buffer, &diff).unwrap();
5430            let output = presenter.into_inner().unwrap();
5431
5432            // Apply to terminal model and verify all characters are correct
5433            let mut model = TerminalModel::new(width as usize, height as usize);
5434            model.process(&output);
5435
5436            for (&(x, y), &ch) in &expected {
5437                let mut buf = [0u8; 4];
5438                let expected_str = ch.encode_utf8(&mut buf);
5439
5440                if let Some(model_cell) = model.cell(x as usize, y as usize) {
5441                    prop_assert_eq!(
5442                        model_cell.text.as_str(),
5443                        expected_str,
5444                        "DP cost model: character mismatch at ({}, {})", x, y
5445                    );
5446                }
5447            }
5448        }
5449    }
5450
5451    #[test]
5452    fn trim_runs_to_row_widths_clips_trailing_blanks_and_records_el() {
5453        let mut buffer = Buffer::new(20, 3);
5454        for (x, ch) in "hello".chars().enumerate() {
5455            buffer.set_raw(x as u16, 0, Cell::from_char(ch));
5456        }
5457        // Row 1 is completely blank (occupied width 0).
5458        // Row 2 has text up to col 3.
5459        for (x, ch) in "abc".chars().enumerate() {
5460            buffer.set_raw(x as u16, 2, Cell::from_char(ch));
5461        }
5462
5463        let diff = BufferDiff::full(20, 3);
5464        let mut presenter = test_presenter();
5465        presenter.prepare_runs(&diff);
5466        let mut el_rows = Vec::new();
5467        presenter.trim_runs_to_row_widths(&[5, 0, 3], Some(&mut el_rows));
5468        presenter.emit_diff_runs(&buffer, None, None).unwrap();
5469        presenter.finish_frame().unwrap();
5470        let output = presenter.into_inner().unwrap();
5471        let text = String::from_utf8_lossy(&output);
5472
5473        assert!(text.contains("hello"));
5474        assert!(text.contains("abc"));
5475        assert!(
5476            !text.contains("hello "),
5477            "trailing uncolored spaces must not be emitted: {text:?}"
5478        );
5479        assert_eq!(el_rows, vec![(0, 5), (1, 0), (2, 3)]);
5480    }
5481}