retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use super::cache::RenderCache;
use crate::screen::cell::Row;
#[cfg(test)]
use crate::screen::grid::Grid;
use crate::screen::grid::{ActiveCharset, Charset, MouseEncoding, TerminalModes};
use crate::screen::style::{write_u16, StyleId, StyleTable};

pub(super) fn hash_row(row: &Row) -> u64 {
    let mut hasher = DefaultHasher::new();
    row.hash(&mut hasher);
    hasher.finish()
}

/// Render a single row of cells as ANSI bytes with SGR codes, resolving each
/// cell's `StyleId` to a `Style` via the supplied closure.
/// Returns empty Vec for fully blank lines.
///
/// Style transitions are detected by comparing `StyleId`s (not `Style` values),
/// so the closure is only invoked when the interned id actually changes.
pub(in crate::screen) fn render_line_with(
    row: &Row,
    resolve: impl Fn(StyleId) -> crate::screen::style::Style,
) -> Vec<u8> {
    let content_len = row.content_len();
    if content_len == 0 {
        return Vec::new();
    }

    let mut out = Vec::new();
    let mut current_id = StyleId::default();
    for g in row.graphemes() {
        if (g.col as usize) >= content_len {
            break;
        }
        if g.style_id != current_id {
            resolve(g.style_id).write_sgr_with_reset_to(&mut out);
            current_id = g.style_id;
        }
        let mut buf = [0u8; 4];
        out.extend_from_slice(g.c.encode_utf8(&mut buf).as_bytes());
        for &mark in g.combining {
            out.extend_from_slice(mark.encode_utf8(&mut buf).as_bytes());
        }
    }
    if !current_id.is_default() {
        out.extend_from_slice(b"\x1b[0m");
    }
    out
}

/// Render a single row of cells as ANSI bytes with SGR codes.
/// Returns empty Vec for fully blank lines.
pub(in crate::screen) fn render_line(row: &Row, styles: &StyleTable) -> Vec<u8> {
    render_line_with(row, |id| styles.get(id))
}

/// Emit a single boolean DEC private mode sequence.
fn emit_dec_mode(out: &mut Vec<u8>, code: u16, enabled: bool) {
    out.extend_from_slice(b"\x1b[?");
    write_u16(out, code);
    out.push(if enabled { b'h' } else { b'l' });
}

/// Emit a character set designation: ESC `slot` `final`.
/// `slot` is `(` for G0, `)` for G1.
fn emit_charset(out: &mut Vec<u8>, slot: u8, charset: Charset) {
    out.push(0x1b);
    out.push(slot);
    out.push(match charset {
        Charset::Ascii => b'B',
        Charset::LineDrawing => b'0',
    });
}

/// Emit escape sequences for one mode, unconditionally.
fn emit_mode(out: &mut Vec<u8>, modes: &TerminalModes) {
    // Cursor shape (DECSCUSR)
    out.extend_from_slice(b"\x1b[");
    out.push(b'0' + modes.cursor_shape.to_param());
    out.extend_from_slice(b" q");

    // Boolean DEC private modes
    emit_dec_mode(out, 1, modes.cursor_key_mode);
    emit_dec_mode(out, 6, modes.origin_mode);
    emit_dec_mode(out, 7, modes.autowrap_mode);
    emit_dec_mode(out, 2004, modes.bracketed_paste);

    // Mouse modes: emit each independently
    emit_dec_mode(out, 1000, modes.mouse_modes.click);
    emit_dec_mode(out, 1002, modes.mouse_modes.button);
    emit_dec_mode(out, 1003, modes.mouse_modes.any);

    // Mouse encoding
    emit_mouse_encoding(out, modes.mouse_encoding);

    emit_dec_mode(out, 1004, modes.focus_reporting);

    // Keypad mode (not DEC private — uses ESC = / ESC >)
    out.extend_from_slice(if modes.keypad_app_mode {
        b"\x1b="
    } else {
        b"\x1b>"
    });

    // Character set designations (G0/G1)
    emit_charset(out, b'(', modes.g0_charset);
    emit_charset(out, b')', modes.g1_charset);

    // Active charset: SI (0x0F) for G0, SO (0x0E) for G1
    out.push(match modes.active_charset {
        ActiveCharset::G0 => 0x0F, // SI
        ActiveCharset::G1 => 0x0E, // SO
    });
}

/// Emit mouse encoding sequence for the given encoding mode.
fn emit_mouse_encoding(out: &mut Vec<u8>, encoding: MouseEncoding) {
    match encoding {
        MouseEncoding::Sgr => {
            out.extend_from_slice(b"\x1b[?1005l");
            out.extend_from_slice(b"\x1b[?1006h");
        }
        MouseEncoding::Utf8 => {
            out.extend_from_slice(b"\x1b[?1006l");
            out.extend_from_slice(b"\x1b[?1005h");
        }
        MouseEncoding::X10 => out.extend_from_slice(b"\x1b[?1006l\x1b[?1005l"),
    }
}

/// Emit only mode sequences that changed since last render.
fn emit_mode_delta(out: &mut Vec<u8>, modes: &TerminalModes, prev: &TerminalModes) {
    if modes.cursor_shape != prev.cursor_shape {
        out.extend_from_slice(b"\x1b[");
        out.push(b'0' + modes.cursor_shape.to_param());
        out.extend_from_slice(b" q");
    }
    if modes.cursor_key_mode != prev.cursor_key_mode {
        emit_dec_mode(out, 1, modes.cursor_key_mode);
    }
    if modes.origin_mode != prev.origin_mode {
        emit_dec_mode(out, 6, modes.origin_mode);
    }
    if modes.autowrap_mode != prev.autowrap_mode {
        emit_dec_mode(out, 7, modes.autowrap_mode);
    }
    if modes.bracketed_paste != prev.bracketed_paste {
        emit_dec_mode(out, 2004, modes.bracketed_paste);
    }
    if modes.mouse_modes.click != prev.mouse_modes.click {
        emit_dec_mode(out, 1000, modes.mouse_modes.click);
    }
    if modes.mouse_modes.button != prev.mouse_modes.button {
        emit_dec_mode(out, 1002, modes.mouse_modes.button);
    }
    if modes.mouse_modes.any != prev.mouse_modes.any {
        emit_dec_mode(out, 1003, modes.mouse_modes.any);
    }
    if modes.mouse_encoding != prev.mouse_encoding {
        emit_mouse_encoding(out, modes.mouse_encoding);
    }
    if modes.focus_reporting != prev.focus_reporting {
        emit_dec_mode(out, 1004, modes.focus_reporting);
    }
    if modes.keypad_app_mode != prev.keypad_app_mode {
        out.extend_from_slice(if modes.keypad_app_mode {
            b"\x1b="
        } else {
            b"\x1b>"
        });
    }
    if modes.g0_charset != prev.g0_charset {
        emit_charset(out, b'(', modes.g0_charset);
    }
    if modes.g1_charset != prev.g1_charset {
        emit_charset(out, b')', modes.g1_charset);
    }
    if modes.active_charset != prev.active_charset {
        out.push(match modes.active_charset {
            ActiveCharset::G0 => 0x0F, // SI
            ActiveCharset::G1 => 0x0E, // SO
        });
    }
}

/// Render the full screen grid as ANSI bytes (Grid path).
/// Test-only helper retained so the render module's tests can drive a raw
/// [`Grid`] directly; production code goes through [`AnsiRenderer`].
#[cfg(test)]
pub(in crate::screen) fn render_screen(
    grid: &Grid,
    title: &str,
    full: bool,
    cache: &mut RenderCache,
) -> Vec<u8> {
    render_screen_impl(grid, title, &[], full, cache)
}

/// Render the screen (Grid path) with scrollback lines injected into the real
/// terminal's native scrollback buffer. Test-only helper (see `render_screen`).
#[cfg(test)]
pub(in crate::screen) fn render_screen_with_scrollback(
    grid: &Grid,
    title: &str,
    scrollback: &[Vec<u8>],
    cache: &mut RenderCache,
) -> Vec<u8> {
    render_screen_impl(grid, title, scrollback, true, cache)
}

/// Inject scrollback lines into the terminal's native scrollback buffer.
/// Emitted OUTSIDE the synchronized output block — some terminals (Blink/hterm)
/// buffer all sync'd output atomically, preventing intermediate scroll operations
/// from pushing content into native scrollback.
fn render_scrollback(out: &mut Vec<u8>, rows: u16, scrollback: &[Vec<u8>]) {
    let rows_usize = rows as usize;
    out.extend_from_slice(b"\x1b[?25l\x1b[r");

    for chunk in scrollback.chunks(rows_usize) {
        for (i, line) in chunk.iter().enumerate() {
            out.extend_from_slice(b"\x1b[");
            write_u16(out, (i + 1) as u16);
            out.extend_from_slice(b";1H\x1b[0m");
            out.extend_from_slice(line);
            out.extend_from_slice(b"\x1b[K");
        }
        if chunk.len() < rows_usize {
            for i in chunk.len()..rows_usize {
                out.extend_from_slice(b"\x1b[");
                write_u16(out, (i + 1) as u16);
                out.extend_from_slice(b";1H\x1b[2K");
            }
        }
        out.extend_from_slice(b"\x1b[");
        write_u16(out, rows);
        out.extend_from_slice(b";1H");
        out.extend(std::iter::repeat_n(b'\n', chunk.len()));
    }
}

/// Emit scroll region, cursor position, terminal modes, and window title.
/// Cursor visibility is handled separately after no-op detection because
/// the sync block unconditionally hides the cursor at the start.
fn render_modes_title_cursor(
    out: &mut Vec<u8>,
    scroll_region: (u16, u16),
    modes: &TerminalModes,
    cursor_pos: (u16, u16),
    title: &str,
    full: bool,
    cache: &mut RenderCache,
) {
    // Scroll region (DECSTBM): must be emitted BEFORE cursor position because
    // setting the scroll region resets the cursor to home.
    if full || cache.last_scroll_region != Some(scroll_region) {
        out.extend_from_slice(b"\x1b[");
        write_u16(out, scroll_region.0 + 1);
        out.push(b';');
        write_u16(out, scroll_region.1 + 1);
        out.push(b'r');
        cache.last_scroll_region = Some(scroll_region);
    }

    // Mode sequences before cursor position: emit_mode emits \x1b[?6h/l (DECOM)
    // which homes the cursor on xterm/VTE. CUP must come AFTER modes so it is
    // not overridden by cursor-homing side effects of DECOM state changes.
    match &cache.last_modes {
        Some(prev) if !full => emit_mode_delta(out, modes, prev),
        _ => emit_mode(out, modes),
    }
    cache.last_modes = Some(modes.clone());

    // Cursor position: emitted AFTER modes so it overrides any cursor-homing
    // caused by DECOM (?6) or other mode changes.
    //
    // The cursor row is stored absolutely. With origin mode (DECOM, ?6) active
    // the outer terminal interprets the CUP row relative to the scroll region
    // top, so emit it origin-relative (subtract scroll_top, clamped at 0).
    if full || cache.last_cursor != Some(cursor_pos) {
        let cup_row = if modes.origin_mode {
            cursor_pos.1.saturating_sub(scroll_region.0)
        } else {
            cursor_pos.1
        };
        out.extend_from_slice(b"\x1b[");
        write_u16(out, cup_row + 1);
        out.push(b';');
        write_u16(out, cursor_pos.0 + 1);
        out.push(b'H');
        cache.last_cursor = Some(cursor_pos);
    }

    // Window title: emit on full render (client may have stale title) or when changed.
    // Sanitized to prevent OSC injection.
    if full || title != cache.last_title {
        out.extend_from_slice(b"\x1b]2;");
        for &b in title.as_bytes() {
            if b >= 0x20 && b != 0x7f {
                out.push(b);
            }
        }
        out.push(0x07);
        cache.last_title = title.to_string();
    }
}

#[cfg(test)]
fn render_screen_impl(
    grid: &Grid,
    title: &str,
    scrollback: &[Vec<u8>],
    full: bool,
    cache: &mut RenderCache,
) -> Vec<u8> {
    let capacity = if full || !scrollback.is_empty() {
        grid.cols() as usize * grid.rows() as usize * 4
    } else {
        1024
    };
    let mut out = Vec::with_capacity(capacity);

    if !scrollback.is_empty() {
        render_scrollback(&mut out, grid.rows(), scrollback);
        cache.invalidate();
    }

    let full = full || !scrollback.is_empty();

    render_core(
        &mut out,
        grid.visible_rows(),
        grid.visible_row_count(),
        |id| grid.style_table().get(id),
        grid.scroll_region(),
        grid.modes(),
        grid.cursor_pos(),
        grid.cursor_visible(),
        title,
        full,
        cache,
    );
    out
}

/// Twin of [`render_screen_impl`] driven by the [`TerminalEmulator`] trait
/// instead of a concrete [`Grid`].  Shares everything below the accessor layer
/// so the trait path and the Grid path produce byte-identical output.
pub(in crate::screen) fn render_emulator_impl<
    E: crate::screen::traits::TerminalEmulator + ?Sized,
>(
    emu: &E,
    scrollback: &[Vec<u8>],
    full: bool,
    cache: &mut RenderCache,
) -> Vec<u8> {
    let capacity = if full || !scrollback.is_empty() {
        emu.cols() as usize * emu.rows() as usize * 4
    } else {
        1024
    };
    let mut out = Vec::with_capacity(capacity);

    if !scrollback.is_empty() {
        render_scrollback(&mut out, emu.rows(), scrollback);
        cache.invalidate();
    }

    let full = full || !scrollback.is_empty();

    render_core(
        &mut out,
        (0..emu.rows()).map(|y| emu.visible_row(y)),
        emu.rows() as usize,
        |id| emu.resolve_style(id),
        emu.scroll_region(),
        emu.modes(),
        emu.cursor_position(),
        emu.cursor_visible(),
        emu.title(),
        full,
        cache,
    );
    out
}

/// Shared ANSI emitter used by both the server-facing Grid path and the public
/// `AnsiRenderer` emulator path so the two never diverge.
///
/// Appends to `out` (which may already contain scrollback injection emitted
/// OUTSIDE the synchronized block).  Emits the sync block, dirty-tracked rows,
/// scroll region / modes / title / cursor, and closes the sync block — unless
/// the frame is a no-op, in which case `out` is left at its incoming length.
#[allow(clippy::too_many_arguments)]
pub(super) fn render_core<'a>(
    out: &mut Vec<u8>,
    rows: impl Iterator<Item = &'a Row>,
    num_rows: usize,
    resolve_style: impl Fn(StyleId) -> crate::screen::style::Style,
    scroll_region: (u16, u16),
    modes: &TerminalModes,
    cursor_pos: (u16, u16),
    cursor_visible: bool,
    title: &str,
    full: bool,
    cache: &mut RenderCache,
) {
    use crate::screen::style::Style;

    // Remember length before render payload to detect no-op (the incoming
    // contents are scrollback injection emitted before the sync block).
    let pre_render_len = out.len();

    // Synchronized output block: begin
    out.extend_from_slice(b"\x1b[?2026h");
    out.extend_from_slice(b"\x1b[?25l");

    if full {
        out.extend_from_slice(b"\x1b[0m\x1b[2J\x1b[H");
        cache.invalidate();
    }

    cache.rows.ensure_len(num_rows);

    for (y, row) in rows.enumerate() {
        let row_dirty = cache.rows.check_row(y, row);
        if !full && !row_dirty {
            continue;
        }

        out.extend_from_slice(b"\x1b[");
        write_u16(out, y as u16 + 1);
        out.extend_from_slice(b";1H");

        let write_len = row.content_len();

        let mut last_style = Style::default();
        for g in row.graphemes() {
            if (g.col as usize) >= write_len {
                break;
            }
            let style = resolve_style(g.style_id);
            if style != last_style {
                style.write_sgr_with_reset_to(out);
                last_style = style;
            }
            let mut buf = [0u8; 4];
            out.extend_from_slice(g.c.encode_utf8(&mut buf).as_bytes());
            for &mark in g.combining {
                out.extend_from_slice(mark.encode_utf8(&mut buf).as_bytes());
            }
        }

        // Reset SGR; erase to EOL only for incremental (full already cleared via \x1b[2J)
        out.extend_from_slice(if full {
            b"\x1b[0m" as &[u8]
        } else {
            b"\x1b[0m\x1b[K"
        });
    }

    render_modes_title_cursor(out, scroll_region, modes, cursor_pos, title, full, cache);

    // Cursor visibility is handled AFTER no-op detection because the sync
    // block unconditionally hides the cursor (\x1b[?25l) at the start.
    // If we send any output, we must restore cursor visibility at the end.
    // Caching cursor visibility would cause the cursor to stay hidden on
    // subsequent renders where only rows changed.

    // No-op detection: nothing emitted besides sync header AND cursor
    // visibility unchanged — safe to skip the entire frame.
    let header_len = pre_render_len + b"\x1b[?2026h\x1b[?25l".len();
    if out.len() == header_len && cache.last_cursor_visible == Some(cursor_visible) {
        out.truncate(pre_render_len);
        return;
    }
    cache.last_cursor_visible = Some(cursor_visible);

    // Restore cursor visibility (we always hide at sync start).
    // When cursor should be hidden, the sync-start \x1b[?25l suffices.
    if cursor_visible {
        out.extend_from_slice(b"\x1b[?25h");
    }

    // Close synchronized output block.
    out.extend_from_slice(b"\x1b[?2026l");
}