//! Cell-based terminal renderer. //! //! Port of ultraviolet's `TerminalRenderer` (terminal_renderer.go, //! terminal_renderer_hashmap.go, terminal_renderer_hardscroll.go) as a single //! file — Zig has no cross-file methods without circular imports (Brain //! decision #2). It diff-grids a `RenderBuffer` against an internal model of //! the terminal and emits the minimal ANSI to transition to the new state. //! //! The pending output is a `std.Io.Writer.Allocating`; every sequence goes //! through the `*Writer` face so the `ansi.zig` / `Style.writeDiff` builders //! can be reused. `flush` hands the bytes to the sink writer. //! //! Deviations from uv (see Brain.md Phase 7 notes): //! - Color-profile downsampling matches uv: `updatePen` converts both the old //! and new styles via `colorprofile.convertStyle` before the pen diff. The //! renderer defaults to `.true_color` (passthrough); `setColorProfile` //! switches it at runtime. //! - Move-sequence candidates are built in a fixed scratch; a candidate that //! doesn't fit is skipped (CUP is always the baseline). uv used unbounded //! `strings.Builder`s. The overwrite (cell-content) candidate is limited to //! 512 bytes. //! - Cursor positions are `i32` (uv used `int`); grid indices are `ir.Size` and //! bounds-checked through the `?*Cell` accessors. //! //! Hash values are FNV-1a over the concatenated cell contents instead of //! Go's `hash/maphash`. It only matters that equal lines hash equal; this is //! deterministic and allocation-free. //! The cell-based terminal renderer. See Brain.md for the port plan. const std = @import("std"); const ir = @import("root.zig"); const Allocator = std.mem.Allocator; const Writer = std.Io.Writer; const Line = ir.Line; const Profile = ir.Profile; const TabStops = ir.TabStops; const RenderBuffer = ir.RenderBuffer; const Buffer = ir.Buffer; const Method = ir.width.Method; const Screen = ir.Screen; const Size = ir.Size; const Cell = ir.Cell; const Style = ir.Style; const styled = ir.styled; const TerminalRenderer = @This(); /// ANSI control characters referenced by the renderer. const BS = ir.ansi.BS; const LF = ir.ansi.LF; const CR = ir.ansi.CR; const US = ir.ansi.US; const DEL = ir.ansi.DEL; allocator: Allocator, /// The sink that `flush` writes the pending output to. sink: Writer, /// Pending output buffer (uv's `bytes.Buffer`). out: Writer.Allocating, /// Model of the current screen contents. curbuf: ?RenderBuffer, /// Tab stops for hard-tab cursor movements (null disables hard tabs). tabs: ?TabStops, oldhash: []u64, newhash: []u64, hashtab: []HashEntry, oldnum: []?Size, cur: Cursor, saved: Cursor, flags: Flags, method: Method, term: []const u8, profile: Profile = .true_color, clear: bool, caps: Caps, at_phantom: bool, line_had_wide: bool, /// Scratch for move-sequence candidate building. seq_scratch: [4096]u8, /// Creates a renderer for `term` (the `TERM` value) writing to `sink`. /// Mirrors `NewTerminalRenderer(w, env)`. pub fn init(allocator: Allocator, sink: Writer, term: []const u8) TerminalRenderer { return .{ .allocator = allocator, .sink = sink, .out = .init(allocator), .curbuf = null, .tabs = null, .oldhash = &.{}, .newhash = &.{}, .hashtab = &.{}, .oldnum = &.{}, .cur = .{ .cell = .space, .pos = null }, .saved = .{ .cell = .space, .pos = null }, .flags = .{}, .method = .wcwidth, .term = term, .clear = false, .caps = xtermCaps(term), .at_phantom = false, .line_had_wide = false, .seq_scratch = undefined, }; } pub fn deinit(self: *TerminalRenderer) void { if (self.curbuf) |*cb| cb.deinit(); if (self.tabs) |*tab| tab.deinit(); self.allocator.free(self.oldhash); self.allocator.free(self.newhash); self.allocator.free(self.hashtab); self.allocator.free(self.oldnum); self.out.deinit(); self.* = undefined; } pub fn setFullscreen(self: *TerminalRenderer, flag: bool) void { self.flags.fullscreen = flag; } pub fn fullscreen(self: *TerminalRenderer) bool { return self.flags.fullscreen; } pub fn setRelativeCursor(self: *TerminalRenderer, flag: bool) void { self.flags.relative_cursor = flag; } pub fn setMapNewline(self: *TerminalRenderer, flag: bool) void { self.flags.map_newline = flag; } pub fn setScrollOptim(self: *TerminalRenderer, flag: bool) void { self.flags.scroll_optim = flag; } pub fn setBackspace(self: *TerminalRenderer, flag: bool) void { self.caps.bs = flag; } /// Sets whether the terminal measures width via Unicode grapheme /// clustering (DEC mode 2027). Switches the width method accordingly. pub fn setGraphemeWidth(self: *TerminalRenderer, flag: bool) void { self.flags.grapheme_width = flag; self.method = if (flag) .grapheme else .wcwidth; } /// Sets the tab stops for the terminal and enables hard-tab movement /// optimizations. A null width disables hard tabs. Ignored when the /// terminal type is "linux" (it does not support hard tabs). /// Mirrors `SetTabStops(width)`. pub fn setTabStops(self: *TerminalRenderer, width: ?usize) !void { if (std.mem.startsWith(u8, self.term, "linux")) { self.caps.ht = false; return; } if (self.tabs) |*tab| { tab.deinit(); self.tabs = null; } if (width) |w| { self.tabs = try .default(self.allocator, w); self.caps.ht = self.tabs != null; } else { self.caps.ht = false; } } /// Saves the current cursor position and styles. pub fn saveCursor(self: *TerminalRenderer) void { self.saved = self.cur; } /// Restores the saved cursor position and styles. pub fn restoreCursor(self: *TerminalRenderer) void { self.cur = self.saved; } /// Queues entering the alternate screen buffer. pub fn enterAltScreen(self: *TerminalRenderer) !void { self.saveCursor(); try self.emitAll(ir.ansi.setModeAltScreenSaveCursor); self.setFullscreen(true); self.setRelativeCursor(false); self.erase(); } /// Queues exiting the alternate screen buffer. pub fn exitAltScreen(self: *TerminalRenderer) !void { self.erase(); self.setRelativeCursor(true); self.setFullscreen(false); try self.emitAll(ir.ansi.resetModeAltScreenSaveCursor); self.restoreCursor(); } /// Hides the terminal cursor. pub fn hideCursor(self: *TerminalRenderer) !void { try self.emitAll("\x1b[?25l"); } /// Shows the terminal cursor. pub fn showCursor(self: *TerminalRenderer) !void { try self.emitAll("\x1b[?25h"); } /// Queues a full erase on the next render. pub fn erase(self: *TerminalRenderer) void { self.clear = true; } /// Forces a full redraw on the next render (Erase + Render). pub fn redraw(self: *TerminalRenderer, newbuf: *Buffer.RenderBuffer) !void { self.clear = true; return self.render(newbuf); } /// The number of bytes pending in the output buffer. pub fn buffered(self: *TerminalRenderer) usize { return self.out.writer.buffered().len; } /// Writes the pending output to the sink and resets the buffer. pub fn flush(self: *TerminalRenderer) !void { var list = self.out.toArrayList(); defer list.deinit(self.allocator); if (list.items.len > 0) _ = try self.sink.write(list.items); } /// Queues raw bytes to the output buffer. pub fn write(self: *TerminalRenderer, data: []const u8) !void { _ = try self.out.writer.write(data); } /// Queues a raw string to the output buffer. pub fn writeString(self: *TerminalRenderer, s: []const u8) !void { try self.out.writer.writeAll(s); } /// Returns the current cursor position in the screen buffer, or null when /// the position is unknown (an absolute move will be required). pub fn position(self: *TerminalRenderer) ?Pos { return self.cur.pos; } /// Sets the logical cursor position (both buffers). pub fn setPosition(self: *TerminalRenderer, x: Size, y: Size) void { self.cur.pos = .{ .x = x, .y = y }; } /// Writes the shortest sequence to move the cursor to the given position, /// without any buffer checks. pub fn moveTo(self: *TerminalRenderer, x: Size, y: Size) !void { try self.move(null, x, y); } /// Adds the lines of `str` to the top of the screen. The prepended lines /// are not managed by the renderer and will not be cleared or updated. pub fn prependString(self: *TerminalRenderer, newbuf: *RenderBuffer, str: []const u8) !void { if (str.len == 0 or newbuf.height() == 0) return; const w = newbuf.width(); const h = newbuf.height(); try self.move(newbuf, 0, @intCast(h - 1)); var lines = std.mem.splitScalar(u8, str, '\n'); var offset: usize = 0; while (lines.next()) |line| { const line_width = self.method.stringWidth(line); if (w > 0 and line_width > w) offset += (line_width / w); if (line_width == 0 or line_width % w != 0) offset += 1; } var i: usize = 0; while (i < offset) : (i += 1) try self.out.writer.writeByte('\n'); if (self.cur.pos) |*p| p.y += @intCast(offset); try self.moveCursor(newbuf, 0, 0, false); try self.emitCsiParam(offset, 'L'); lines.reset(); while (lines.next()) |line| { try self.out.writer.writeAll(line); try self.out.writer.writeAll("\r\n"); } } /// Updates the terminal screen tab stops (for hard tab optimizations) and /// invalidates the cursor model when the renderer can recover from it. pub fn resize(self: *TerminalRenderer, width: usize) !void { if (self.tabs) |tab| try tab.resize(width); if (!self.flags.relative_cursor) { self.cur.pos = null; self.at_phantom = false; } } fn emitAll(self: *TerminalRenderer, data: []const u8) !void { try self.out.writer.writeAll(data); } /// Writes `CSI n F` with the parameter omitted when n <= 1 (matches /// `ansi.writeCsiParam`). fn emitCsiParam(self: *TerminalRenderer, n: usize, final: u8) !void { try self.out.writer.writeByte(0x1b); try self.out.writer.writeByte('['); if (n > 1) try self.out.writer.print("{d}", .{n}); try self.out.writer.writeByte(final); } /// Writes `CSI n F` with the parameter omitted when n <= 0 (matches /// `ansi.writeCsiPos`). fn emitCsiPos(self: *TerminalRenderer, n: usize, final: u8) !void { try self.out.writer.writeByte(0x1b); try self.out.writer.writeByte('['); if (n > 0) try self.out.writer.print("{d}", .{n}); try self.out.writer.writeByte(final); } /// Returns a blank cell with the current cursor background color /// (mirrors `clearBlank`). fn clearBlank(self: *TerminalRenderer) Cell { return self.cur.cell; } /// Updates the cursor pen styles from the given cell. A null cell resets /// the style/hyperlink. Mirrors `updatePen`. On a null cell the style is /// not reset when the cell carries no style (there is nothing to reset). fn updatePen(self: *TerminalRenderer, cell: ?Cell) !void { if (cell == null) { if (!self.cur.cell.style.isZero()) { try self.emitAll(ir.ansi.resetStyle); self.cur.cell.style = .{}; } if (!self.cur.cell.link.isZero()) { _ = try ir.ansi.resetHyperlink(&self.out.writer, ""); self.cur.cell.link = .{}; } return; } const new_style_full = cell.?.style; const new_link = cell.?.link; const old_style_full = self.cur.cell.style; const old_link = self.cur.cell.link; // Downsample the styles to the terminal's color profile before diffing // so the emitted sequences match its capabilities. The model keeps the // original (full) styles so a later profile change can re-render. Mirrors // uv `ConvertStyle`/`ConvertLink`. const new_style = new_style_full.convert(self.profile); const old_style = old_style_full.convert(self.profile); if (!new_style.equal(old_style)) { var seq: [256]u8 = undefined; var sw: Writer = .fixed(&seq); const n = try Style.writeDiff(old_style, new_style, &sw); if (new_style.isZero() and n > ir.ansi.resetStyle.len) { try self.emitAll(ir.ansi.resetStyle); } else { try self.emitAll(seq[0..n]); } self.cur.cell.style = new_style_full; } if (self.profile == .no_tty or self.profile == .unknown) { if (!old_link.isZero()) { _ = try ir.ansi.resetHyperlink(&self.out.writer, ""); self.cur.cell.link = .{}; } } else if (!new_link.equal(old_link)) { _ = try ir.ansi.setHyperlink(&self.out.writer, new_link.url, new_link.params); self.cur.cell.link = new_link; } } /// Writes a cell at the current cursor position, handling the lower-right /// corner specially. Mirrors `putCell`. fn putCell(self: *TerminalRenderer, newbuf: *RenderBuffer, cell: ?Cell) !void { const width = newbuf.width(); const height = newbuf.height(); if (self.flags.fullscreen and self.cur.pos.?.x == width -| 1 and self.cur.pos.?.y == height -| 1) { if (width > 0 and height > 0) try self.putCellLR(newbuf, cell); } else { try self.putAttrCell(newbuf, cell); } } /// Wraps the cursor to the next line assuming auto-wrap is enabled. fn wrapCursor(self: *TerminalRenderer) void { self.cur.pos.?.x = 0; self.cur.pos.?.y += 1; } /// Writes a single cell, tracking the phantom (pending-wrap) state. fn putAttrCell(self: *TerminalRenderer, newbuf: *RenderBuffer, cell: ?Cell) !void { if (cell != null and cell.?.width == 0) { // Zero-width cells are wide placeholders, never written. return; } if (self.at_phantom) { self.wrapCursor(); self.at_phantom = false; } try self.updatePen(cell); var width: usize = 1; if (cell) |c| { try self.emitAll(c.content); width = c.width; } else { try self.out.writer.writeByte(' '); } self.cur.pos.?.x += @intCast(width); if (self.cur.pos.?.x >= newbuf.width()) { self.at_phantom = true; } if (width > 1) { self.line_had_wide = true; } } /// Writes a cell at the lower-right corner without wrapping. fn putCellLR(self: *TerminalRenderer, newbuf: *RenderBuffer, cell: ?Cell) !void { const cur_x = self.cur.pos.?.x; if (cell == null or !cell.?.isWidePlaceholder()) { try self.emitAll(ir.ansi.resetModeAutoWrap); try self.putAttrCell(newbuf, cell); self.at_phantom = false; self.cur.pos.?.x = cur_x; try self.emitAll(ir.ansi.setModeAutoWrap); } } /// Moves the cursor to (x, y) writing the cheapest sequence. Mirrors the /// `moveCursor` free function in uv. Returns a slice of the internal /// scratch, valid until the next move or render. fn moveSeq(self: *TerminalRenderer, newbuf: ?*RenderBuffer, x: Size, y: Size, overwrite: bool) []const u8 { const known = self.cur.pos; // `-1` marks an unknown origin for `relativeCursorMove`; the model // stores it as `null`, never as a bogus coordinate. const fx: i32 = if (known) |p| @intCast(p.x) else -1; const fy: i32 = if (known) |p| @intCast(p.y) else -1; var best = Sink{ .buf = self.seq_scratch[0..1024] }; if (!self.flags.relative_cursor) { var width: i64 = -1; if (self.tabs != null) width = @intCast(self.tabs.?.width()); if (newbuf != null and width == -1) width = @intCast(newbuf.?.width()); // Method #0: use CUP if the distance is long. if (fx == -1 or fy == -1 or width == -1 or notLocal(width, fx, fy, x, y)) { var tmp: [32]u8 = undefined; var sw = Sink{ .buf = &tmp }; sw.add("\x1b["); if (y + 1 > 0) sw.addNumber(@intCast(y + 1)); sw.addByte(';'); if (x + 1 > 0) sw.addNumber(@intCast(x + 1)); sw.addByte('H'); best.add(sw.slice()); return best.slice(); } } // Method #0: CUP is the baseline any local optimization must beat. { var tmp: [32]u8 = undefined; var sw = Sink{ .buf = &tmp }; sw.add("\x1b["); if (y + 1 > 0) sw.addNumber(@intCast(y + 1)); sw.addByte(';'); if (x + 1 > 0) sw.addNumber(@intCast(x + 1)); sw.addByte('H'); best.add(sw.slice()); } // Optimize based on options. var trials: u8 = 0; if (self.caps.ht) trials |= 2; if (self.caps.bs) trials |= 1; var i: u8 = 0; while (i <= trials) : (i += 1) { if (i & (~trials) != 0) continue; // skip unsupported combos const use_hard_tabs = (i & 2) != 0; const use_backspace = (i & 1) != 0; const cand = self.seq_scratch[1024..3072]; var nseq1 = Sink{ .buf = cand }; relativeCursorMove(self, newbuf, &nseq1, fx, fy, @intCast(x), @intCast(y), overwrite, use_hard_tabs, use_backspace); if (!nseq1.overflow and nseq1.len < best.len) { @memcpy(self.seq_scratch[0..nseq1.len], nseq1.slice()); best.len = nseq1.len; } // Method #2: CR and local movement. var nseq2 = Sink{ .buf = cand }; nseq2.addByte(CR); relativeCursorMove(self, newbuf, &nseq2, 0, fy, @intCast(x), @intCast(y), overwrite, use_hard_tabs, use_backspace); if (!nseq2.overflow and nseq2.len < best.len) { @memcpy(self.seq_scratch[0..nseq2.len], nseq2.slice()); best.len = nseq2.len; } if (!self.flags.relative_cursor) { // Method #3: home and local movement. var nseq3: Sink = .{ .buf = cand }; nseq3.add(ir.ansi.cursorHomePosition); relativeCursorMove(self, newbuf, &nseq3, 0, 0, @intCast(x), @intCast(y), overwrite, use_hard_tabs, use_backspace); if (!nseq3.overflow and nseq3.len < best.len) { @memcpy(self.seq_scratch[0..nseq3.len], nseq3.slice()); best.len = nseq3.len; } } } return best.slice(); } /// Moves the cursor to the specified position, updating the model and /// emitting the chosen sequence. Mirrors uv `moveCursor`. fn moveCursor(self: *TerminalRenderer, newbuf: ?*RenderBuffer, x: Size, y: Size, overwrite: bool) !void { if (!self.flags.fullscreen and self.flags.relative_cursor and self.cur.pos == null) { // First cursor movement in inline mode: carriage return first. try self.out.writer.writeByte(CR); self.cur.pos = .{ .x = 0, .y = 0 }; } const seq = self.moveSeq(newbuf, x, y, overwrite); try self.emitAll(seq); self.cur.pos = .{ .x = x, .y = y }; } /// Moves the cursor to a position in the buffers, performing autowrap and /// pen/phantom bookkeeping. Mirrors uv `move`. fn move(self: *TerminalRenderer, newbuf: ?*RenderBuffer, x_in: Size, y_in: Size) !void { var x: i64 = x_in; var y: i64 = y_in; var width: i64 = 0; var height: i64 = 0; if (self.curbuf) |cb| { width = @intCast(cb.width()); height = @intCast(cb.height()); } if (newbuf) |nb| { width = @max(width, @as(i64, @intCast(nb.width()))); height = @max(height, @as(i64, @intCast(nb.height()))); } if (width > 0 and x >= width) { // Handle autowrap. y += @divTrunc(x, width); x = @rem(x, width); } const blank = self.clearBlank(); const reset_pen = (self.cur.pos == null or y != self.cur.pos.?.y) and !blank.equal(.space); if (reset_pen) try self.updatePen(null); // Reset the phantom-cursor (pending wrap) state. if (self.at_phantom) { self.cur.pos.?.x = 0; try self.out.writer.writeByte(CR); self.at_phantom = false; } if (height > 0) { if (self.cur.pos) |*p| { if (p.y > height - 1) { p.y = @intCast(height - 1); } } if (y > height - 1) { y = height - 1; } } const same = if (self.cur.pos) |p| (x == p.x and y == p.y) else false; if (same) { return; } try self.moveCursor(newbuf, @intCast(x), @intCast(y), true); } /// The cost of using `EL 0`. When the terminal has any capabilities we /// assume BCE (background color erase) so it is nearly free. fn el0Cost(self: *TerminalRenderer) usize { const caps: u12 = @bitCast(self.caps); if (caps != 0) return 0; return ir.ansi.eraseLineRight.len; } /// Inserts `count` cells from `line` at the current cursor position. fn insertCells(self: *TerminalRenderer, newbuf: *RenderBuffer, line: Line, count: usize) !void { const supports_ich = self.caps.ich; if (supports_ich) { try self.emitCsiParam(count, '@'); } else { try self.emitAll(ir.ansi.setModeInsertReplace); } var i: usize = 0; var remaining = count; while (remaining > 0) : (i += 1) { try self.putAttrCell(newbuf, cellVal(line.at(@intCast(i)))); remaining -= 1; } if (!supports_ich) { try self.emitAll(ir.ansi.resetModeInsertReplace); } } /// Deletes `count` cells at the current cursor position, shifting the rest /// of the line left (DCH). fn deleteCells(self: *TerminalRenderer, count: usize) !void { try self.emitCsiParam(count, 'P'); } /// Emits a run of cells, using ECH and REP where profitable. /// Returns whether the cursor is at the end of the interval. fn emitRange(self: *TerminalRenderer, newbuf: *RenderBuffer, line: Line, n_in: usize) !bool { const has_ech = self.caps.ech; const has_rep = self.caps.rep; var n = n_in; var line_var = line; if (has_ech or has_rep) { while (n > 0) { var count: usize = 0; while (n > 1 and !cellEqual(cellVal(line_var.at(0)), cellVal(line_var.at(1)))) { try self.putCell(newbuf, cellVal(line_var.at(0))); line_var = cutLine(line_var, 1); n -= 1; } const cell0 = cellVal(line_var.at(0)); if (n == 1) { try self.putCell(newbuf, cell0); return false; } count = 2; while (count < n and cellEqual(cellVal(line_var.at(@intCast(count))), cell0)) { count += 1; } const ech_len = csiParamLen(count); const cup_len = cupLen(@as(usize, @intCast(self.cur.pos.?.x)) +% count, @as(usize, @intCast(self.cur.pos.?.y))); const rep_len = csiParamLen(count); if (has_ech and count > ech_len + cup_len and canClearWith(cell0)) { try self.updatePen(cell0); try self.emitCsiParam(count, 'X'); // If this is the last cell, we don't need to move the cursor. if (count < n) { try self.move(newbuf, @intCast(@as(u32, self.cur.pos.?.x) + @as(u32, @intCast(count))), self.cur.pos.?.y); } else return true; // cursor in the middle } else if (has_rep and count > rep_len and cell0 != null and cell0.?.content.len == 1 and cell0.?.content[0] >= US and cell0.?.content[0] < DEL) { // REP only repeats the last rune; only single-ASCII cells. const wrap_possible = @as(u32, self.cur.pos.?.x) + @as(u32, @intCast(count)) >= newbuf.width(); var rep_count: usize = count; if (wrap_possible) rep_count -= 1; try self.updatePen(cell0); try self.putCell(newbuf, cell0); rep_count -= 1; // cell0 is a single-width ASCII cell _ = try ir.ansi.repeatPreviousCharacter(&self.out.writer, rep_count); self.cur.pos.?.x += @intCast(rep_count); if (wrap_possible) { try self.putCell(newbuf, cell0); } } else { var i: usize = 0; while (i < count) : (i += 1) { try self.putCell(newbuf, cellVal(line_var.at(@intCast(i)))); } } line_var = cutLine(line_var, count); n -= count; } return false; } var i: usize = 0; while (i < n) : (i += 1) { try self.putCell(newbuf, cellVal(line_var.at(@intCast(i)))); } return false; } /// Puts a range of cells from the old line to the new line, skipping /// identical runs. Returns whether the cursor is at the end of the range. fn putRange(self: *TerminalRenderer, newbuf: *RenderBuffer, old_line: Line, new_line: Line, y: usize, start: usize, end: usize) !bool { if (end < start) return false; // Empty range: nothing to emit. const inline_len: usize = @min(cupLen(start + 1, y + 1), @min(csiPosLen(start + 1), csiParamLen(start + 1))); if ((end - start + 1) > inline_len) { var j = start; var same: usize = 0; var write_start = start; while (j <= end) : (j += 1) { const old_cell = cellVal(old_line.at(@intCast(j))); const new_cell = cellVal(new_line.at(@intCast(j))); if (same == 0 and old_cell != null and new_cell != null and old_cell.?.isWidePlaceholder() and new_cell.?.isWidePlaceholder()) continue; if (cellEqual(old_cell, new_cell)) { same += 1; } else { if (same > end - start) { _ = try self.emitRange(newbuf, cutLine(new_line, write_start), j - same - write_start); try self.move(newbuf, @intCast(j), @intCast(y)); write_start = j; } same = 0; } } const i = try self.emitRange(newbuf, cutLine(new_line, write_start), j - same - write_start); // Always return 1 for the next move after a putRange when we found // identical characters at the end of the interval. if (same == 0) return i; return true; } return self.emitRange(newbuf, cutLine(new_line, start), end - start + 1); } /// Clears the screen from the current cursor position to the end of line. fn clearToEnd(self: *TerminalRenderer, newbuf: *RenderBuffer, blank: ?Cell, force_in: bool) !void { var force = force_in; if (self.cur.pos) |pos| { if (self.curbuf.?.line(pos.y)) |curline| { var j: Size = pos.x; while (j < newbuf.width()) : (j += 1) { const c = cellVal(curline.at(j)); if (!cellEqual(c, blank)) { curline.set(j, blank); force = true; } } } } if (force) { try self.updatePen(blank); const start: Size = if (self.cur.pos) |p| p.x else 0; const count = newbuf.width() - start; if (self.el0Cost() <= count) { try self.emitAll(ir.ansi.eraseLineRight); } else { var i: usize = 0; while (i < count) : (i += 1) { try self.putCell(newbuf, blank); } } } } /// Clears the screen from the current cursor position to the bottom. fn clearToBottom(self: *TerminalRenderer, blank: ?Cell) !void { const pos = self.cur.pos; try self.updatePen(blank); try self.emitAll(ir.ansi.eraseScreenBelow); const w = self.curbuf.?.width(); const h = self.curbuf.?.height(); if (pos) |p| { // Clear the rest of the current line. if (p.x < w) self.curbuf.?.clearArea(.new(p.x, p.y, w - p.x, 1)); // Clear everything below the current line. if (p.y + 1 < h) self.curbuf.?.clearArea(.new(0, p.y + 1, w, h - p.y - 1)); } else if (h > 1) { // Unknown cursor: clear everything below the top line. self.curbuf.?.clearArea(.new(0, 1, w, h - 1)); } } /// Tests if clearing the end of the screen would satisfy part of the /// update. Scans backwards through the lines checking if each is blank /// and one or more are changed. Returns the top line. fn clearBottom(self: *TerminalRenderer, newbuf: *RenderBuffer, total: usize) !usize { if (total <= 0) return 0; var top = total; const last = @min(self.curbuf.?.width(), newbuf.width()); const blank = self.clearBlank(); const can_clear_with_blank = canClearWith(blank); var row: i64 = -1; if (can_clear_with_blank) { var r: i64 = @as(i64, @intCast(total - 1)); while (r >= 0) : (r -= 1) { const old_line = self.curbuf.?.line(@intCast(r)) orelse break; const new_line = newbuf.line(@intCast(r)) orelse break; var col: Size = 0; var ok = true; while (ok and col < last) : (col += 1) { ok = cellEqual(cellVal(new_line.at(col)), blank); } if (!ok) break; col = 0; while (ok and col < last) : (col += 1) { ok = cellEqual(cellVal(old_line.at(col)), blank); } if (!ok) top = @intCast(r); row = r; } if (top < total) { try self.move(newbuf, 0, @intCast(@max(0, @as(i64, @intCast(top -| 1))))); try self.clearToBottom(blank); if (self.oldhash.len > 0 and self.newhash.len > 0 and row >= 0 and row < self.oldhash.len and row < self.newhash.len) { var rr: usize = top; while (rr < newbuf.height() and rr < self.oldhash.len) : (rr += 1) { self.oldhash[rr] = self.newhash[rr]; } } } } return top; } /// Clears the screen and moves the cursor home. fn clearScreen(self: *TerminalRenderer, blank: ?Cell) !void { try self.updatePen(blank); try self.emitAll(ir.ansi.cursorHomePosition); try self.emitAll(ir.ansi.eraseEntireScreen); self.cur.pos = .{ .x = 0, .y = 0 }; self.curbuf.?.fill(blank); } /// Clears everything below (and including) the given row. fn clearBelow(self: *TerminalRenderer, newbuf: *RenderBuffer, blank: ?Cell, row: Size) !void { try self.move(newbuf, 0, row); try self.clearToBottom(blank); } /// Forces a screen redraw from scratch. fn clearUpdate(self: *TerminalRenderer, newbuf: *RenderBuffer) !void { const blank = self.clearBlank(); var non_empty: usize = undefined; if (self.flags.fullscreen) { non_empty = @max(self.curbuf.?.height(), newbuf.height()); try self.clearScreen(blank); } else { non_empty = newbuf.height(); try self.clearBelow(newbuf, blank, 0); } non_empty = try self.clearBottom(newbuf, non_empty); var i: Size = 0; while (i < non_empty and i < newbuf.height()) : (i += 1) { try self.transformLine(newbuf, i); } } /// Repaints a line from scratch: erases the whole line from column 0 then /// writes the new frame's cells. Ports uv's `repaintLine` (see its doc /// comment for why this is needed when a line has a drifting cell). fn repaintLine(self: *TerminalRenderer, newbuf: *RenderBuffer, y: Size) !void { const new_line = newbuf.line(y) orelse return; try self.move(newbuf, 0, @intCast(y)); const blank = self.clearBlank(); try self.updatePen(blank); try self.emitAll(ir.ansi.eraseLineRight); self.cur.pos.?.x = 0; // Write the content cells. The line was just erased, so trailing // blanks need no write. var last: i64 = -1; var x: Size = 0; while (x < newbuf.width()) : (x += 1) { if (new_line.at(x)) |c| { if (!c.isWidePlaceholder() and !cellEqual(c.*, blank)) last = @intCast(x); } } var xi: Size = 0; while (last >= 0 and @as(i64, @intCast(xi)) <= last) : (xi += 1) { try self.putCell(newbuf, cellVal(new_line.at(xi))); } // Adopt the new line as the model of what is on screen. if (self.curbuf.?.line(y)) |old_line| { if (old_line.cells.len == new_line.cells.len) { @memcpy(old_line.cells, new_line.cells); } } } /// Re-anchors the cursor with a single absolute horizontal move after a /// line that contained a wide cell, bounding cursor desync to one line. fn reanchorWideLine(self: *TerminalRenderer, newbuf: *RenderBuffer) void { if (!self.line_had_wide or self.flags.grapheme_width) return; self.line_had_wide = false; if (self.at_phantom) return; const known = self.cur.pos orelse return; if (known.x >= newbuf.width()) return; self.emitCsiPos(@intCast(known.x + 1), 'G') catch {}; } /// Diff-transforms the given line in the model to the corresponding line /// in the new buffer, emitting the minimal sequences. fn transformLine(self: *TerminalRenderer, newbuf: *RenderBuffer, y: Size) !void { var first_cell: i32 = 0; var o_last_cell: i32 = 0; var n_last_cell: i32 = 0; const old_line = self.curbuf.?.line(y) orelse return; const new_line = newbuf.line(y) orelse return; self.line_had_wide = false; defer self.reanchorWideLine(newbuf); // If either frame's line holds a cell that a cell-level diff cannot // safely reposition across, repaint the whole line. See uv's // comment at `lineHasDrift`. if (old_line.*.hasDrift(self.method) or new_line.*.hasDrift(self.method)) { try self.repaintLine(newbuf, y); return; } // Find the first changed cell in the line. var blank = cellVal(new_line.at(0)); // It might be cheaper to clear leading spaces with EL 1 (EL left). if (canClearWith(blank)) { var o_first_cell: i32 = 0; var n_first_cell: i32 = 0; while (o_first_cell < @as(i32, @intCast(self.curbuf.?.width()))) : (o_first_cell += 1) { if (!cellEqual(cellVal(old_line.at(@intCast(o_first_cell))), blank)) break; } while (n_first_cell < @as(i32, @intCast(newbuf.width()))) : (n_first_cell += 1) { if (!cellEqual(cellVal(new_line.at(@intCast(n_first_cell))), blank)) break; } if (n_first_cell == o_first_cell) { first_cell = n_first_cell; // Find the first differing cell. while (first_cell < @as(i32, @intCast(newbuf.width())) and cellEqual(cellVal(new_line.at(@intCast(first_cell))), cellVal(old_line.at(@intCast(first_cell))))) { first_cell += 1; } } else if (o_first_cell > n_first_cell) { first_cell = n_first_cell; } else { first_cell = o_first_cell; const el1_cost = ir.ansi.eraseLineLeft.len; if (el1_cost < @as(usize, @intCast(n_first_cell - o_first_cell))) { if (n_first_cell >= @as(i32, @intCast(newbuf.width()))) { try self.move(newbuf, 0, @intCast(y)); try self.updatePen(blank); try self.emitAll(ir.ansi.eraseLineRight); } else { try self.move(newbuf, @intCast(n_first_cell - 1), @intCast(y)); try self.updatePen(blank); try self.emitAll(ir.ansi.eraseLineLeft); } while (first_cell < n_first_cell) : (first_cell += 1) { old_line.set(@intCast(first_cell), blank); } } } } else { // Find the first differing cell. while (first_cell < @as(i32, @intCast(newbuf.width())) and cellEqual(cellVal(new_line.at(@intCast(first_cell))), cellVal(old_line.at(@intCast(first_cell))))) { first_cell += 1; } } // If we didn't find one, we're done. if (first_cell >= @as(i32, @intCast(newbuf.width()))) return; blank = cellVal(new_line.at(newbuf.width() - 1)); if (blank != null and !canClearWith(blank)) { // Find the last differing cell. n_last_cell = @intCast(newbuf.width() - 1); while (n_last_cell > first_cell and cellEqual(cellVal(new_line.at(@intCast(n_last_cell))), cellVal(old_line.at(@intCast(n_last_cell))))) { n_last_cell -= 1; } if (n_last_cell >= first_cell) { try self.move(newbuf, @intCast(first_cell), @intCast(y)); _ = try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(first_cell), @intCast(n_last_cell)); copyLineInto(old_line, new_line, @intCast(first_cell)); } return; } // Find last non-blank cell in the old line. o_last_cell = @intCast(newbuf.width() - 1); while (o_last_cell > first_cell and cellEqual(cellVal(old_line.at(@intCast(o_last_cell))), blank)) { o_last_cell -= 1; } // Find last non-blank cell in the new line. n_last_cell = @intCast(newbuf.width() - 1); while (n_last_cell > first_cell and cellEqual(cellVal(new_line.at(@intCast(n_last_cell))), blank)) { n_last_cell -= 1; } if (n_last_cell == first_cell and self.el0Cost() < @as(usize, @intCast(o_last_cell - n_last_cell))) { // The new line is blank after (and at) first_cell: maybe use EL. try self.move(newbuf, @intCast(first_cell), @intCast(y)); if (!cellEqual(cellVal(new_line.at(@intCast(first_cell))), blank)) { try self.putCell(newbuf, cellVal(new_line.at(@intCast(first_cell)))); } try self.clearToEnd(newbuf, blank, false); } else if (n_last_cell != o_last_cell and !cellEqual(cellVal(new_line.at(@intCast(n_last_cell))), cellVal(old_line.at(@intCast(o_last_cell))))) { try self.move(newbuf, @intCast(first_cell), @intCast(y)); if (o_last_cell - n_last_cell > @as(i32, @intCast(self.el0Cost()))) { if (try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(first_cell), @intCast(n_last_cell))) { try self.move(newbuf, @intCast(n_last_cell + 1), @intCast(y)); } try self.clearToEnd(newbuf, blank, false); } else { const n = @max(n_last_cell, o_last_cell); _ = try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(first_cell), @intCast(n)); } } else { const n_last_non_blank = n_last_cell; const o_last_non_blank = o_last_cell; // Find the last cells that really differ. // Can be -1 if no cells differ. while (n_last_cell > 0 and o_last_cell > 0 and cellEqual(cellVal(new_line.at(@intCast(n_last_cell))), cellVal(old_line.at(@intCast(o_last_cell))))) { if (!cellEqual(cellVal(new_line.at(@intCast(n_last_cell - 1))), cellVal(old_line.at(@intCast(o_last_cell - 1))))) { break; } n_last_cell -= 1; o_last_cell -= 1; if (n_last_cell == -1 or o_last_cell == -1) break; } const n = @min(o_last_cell, n_last_cell); if (n >= first_cell) { try self.move(newbuf, @intCast(first_cell), @intCast(y)); _ = try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(first_cell), @intCast(n)); } var nn = n; if (o_last_cell < n_last_cell) { const m = @max(n_last_non_blank, o_last_non_blank); if (nn != 0) { while (nn > 0) { const wide = cellVal(new_line.at(@intCast(nn + 1))); if (wide == null or !wide.?.isWidePlaceholder()) break; nn -= 1; o_last_cell -= 1; } } else if (nn >= first_cell and new_line.at(@intCast(nn)) != null and new_line.at(@intCast(nn)).?.width > 1) { var next = cellVal(new_line.at(@intCast(nn + 1))); while (next != null and next.?.isWidePlaceholder()) { nn += 1; o_last_cell += 1; next = cellVal(new_line.at(@intCast(nn + 1))); } } try self.move(newbuf, @intCast(nn + 1), @intCast(y)); const ich_cost: i32 = 3 + n_last_cell - o_last_cell; if (self.caps.ich and (n_last_cell < n_last_non_blank or ich_cost > m - nn)) { _ = try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(nn + 1), @intCast(m)); } else { try self.insertCells(newbuf, cutLine(new_line.*, @intCast(nn + 1)), @intCast(n_last_cell - o_last_cell)); } } else if (o_last_cell > n_last_cell) { try self.move(newbuf, @intCast(nn + 1), @intCast(y)); const dch_cost: i32 = 3 + o_last_cell - n_last_cell; if (@as(i64, dch_cost) > @as(i64, ir.ansi.eraseLineRight.len) + @as(i64, n_last_non_blank) - (@as(i64, nn) + 1)) { if (try self.putRange(newbuf, old_line.*, new_line.*, y, @intCast(nn + 1), @intCast(n_last_non_blank))) { try self.move(newbuf, @intCast(n_last_non_blank + 1), @intCast(y)); } try self.clearToEnd(newbuf, blank, false); } else { try self.updatePen(blank); try self.deleteCells(@intCast(o_last_cell - n_last_cell)); } } } // Update the old line with the new line. copyLineInto(old_line, new_line, @intCast(first_cell)); } /// Recomputes the line hash tables used by the scroll optimizer. fn updateHashmap(self: *TerminalRenderer, newbuf: *RenderBuffer) !void { const height = newbuf.height(); if (self.oldhash.len >= height and self.newhash.len >= height) { // Rehash changed lines. var i: usize = 0; while (i < height) : (i += 1) { if (newbuf.touched.len == 0 or newbuf.touched[i] == .changed) { self.oldhash[i] = self.curbuf.?.line(@intCast(i)).?.*.hash(); self.newhash[i] = newbuf.line(@intCast(i)).?.*.hash(); } } } else { // Rehash all. if (self.oldhash.len != height) { self.allocator.free(self.oldhash); self.oldhash = try self.allocator.alloc(u64, height); } if (self.newhash.len != height) { self.allocator.free(self.newhash); self.newhash = try self.allocator.alloc(u64, height); } for (self.oldhash) |*v| v.* = 0; for (self.newhash) |*v| v.* = 0; var i: usize = 0; while (i < height) : (i += 1) { self.oldhash[i] = self.curbuf.?.line(@intCast(i)).?.*.hash(); self.newhash[i] = newbuf.line(@intCast(i)).?.*.hash(); } } const tab = try self.allocator.alloc(HashEntry, (height + 1) * 2); self.allocator.free(self.hashtab); @memset(tab, .{}); self.hashtab = tab; var i: usize = 0; while (i < height) : (i += 1) { const hashval = self.oldhash[i]; var idx: usize = 0; while (idx < self.hashtab.len and self.hashtab[idx].value != 0) : (idx += 1) { if (self.hashtab[idx].value == hashval) break; } self.hashtab[idx].value = hashval; // in case this is a new hash self.hashtab[idx].old_count += 1; self.hashtab[idx].old_index = @intCast(i); } i = 0; while (i < height) : (i += 1) { const hashval = self.newhash[i]; var idx: usize = 0; while (idx < self.hashtab.len and self.hashtab[idx].value != 0) : (idx += 1) { if (self.hashtab[idx].value == hashval) break; } self.hashtab[idx].value = hashval; self.hashtab[idx].new_count += 1; self.hashtab[idx].new_index = @intCast(i); self.oldnum[i] = new_index; // init old indices slice } // Mark line pairs corresponding to unique hash pairs. var j: usize = 0; while (j < self.hashtab.len and self.hashtab[j].value != 0) : (j += 1) { const hsp = &self.hashtab[j]; if (hsp.old_count == 1 and hsp.new_count == 1 and hsp.old_index != hsp.new_index) { self.oldnum[@intCast(hsp.new_index)] = hsp.old_index; } } self.growHunks(); // Eliminate bad or impossible shifts. var k: i32 = 0; while (k < @as(i32, @intCast(height))) { var start: i32 = 0; var shift: i32 = 0; var size: i32 = 0; while (k < @as(i32, @intCast(height)) and self.oldnum[@intCast(k)] == new_index) { k += 1; } if (k >= @as(i32, @intCast(height))) break; start = k; shift = @as(i32, @intCast(self.oldnum[@intCast(k)].?)) - k; k += 1; while (k < @as(i32, @intCast(height))) { const v = self.oldnum[@intCast(k)]; if (v == new_index or @as(i64, @intCast(v.?)) - k != shift) break; k += 1; } size = k - start; if (size < 3 or size + @min(@divTrunc(size, 8), 2) < absI32(shift)) { var s = start; while (s < k) : (s += 1) { self.oldnum[@intCast(s)] = new_index; } } } // After clearing invalid hunks, try to grow the rest. self.growHunks(); } /// Scrolls the oldhash slice by `n` lines between `top` and `bot`. fn scrollOldhash(self: *TerminalRenderer, n: i32, top: i32, bot: i32) void { if (self.oldhash.len == 0) return; const size: usize = @intCast(bot - top + 1 - absI32(n)); if (n > 0) { // Move existing hashes up. const src: usize = @intCast(top + n); const dst0: usize = @intCast(top); @memmove(self.oldhash[dst0..][0..size], self.oldhash[src..][0..size]); // Recalculate hashes for newly shifted-in lines. var i: i32 = bot; while (i > bot - n) : (i -= 1) { self.oldhash[@intCast(i)] = self.curbuf.?.line(@intCast(i)).?.*.hash(); } } else { // Move existing hashes down. const dst0: usize = @intCast(top - n); const src: usize = @intCast(top); @memmove(self.oldhash[dst0..][0..size], self.oldhash[src..][0..size]); // Recalculate hashes for newly shifted-in lines. var i: i32 = top; while (i < top - n) : (i += 1) { self.oldhash[@intCast(i)] = self.curbuf.?.line(@intCast(i)).?.*.hash(); } } } /// Grows hunks of matching lines to make scrolling contiguous. fn growHunks(self: *TerminalRenderer) void { var back_limit: i32 = 0; // limits for cells to fill var back_ref_limit: i32 = 0; // limit for references var i: i32 = 0; var next_hunk: i32 = 0; const height: i32 = @intCast(self.curbuf.?.height()); while (i < height and self.oldnum[@intCast(i)] == new_index) { i += 1; } while (i < height) { var forward_limit: i32 = 0; var forward_ref_limit: i32 = 0; var end: i32 = 0; const start = i; const shift = @as(i32, @intCast(self.oldnum[@intCast(i)].?)) - i; // Get forward limit. i = start + 1; while (i < height) { const v = self.oldnum[@intCast(i)]; if (v == new_index or @as(i64, @intCast(v.?)) - i != shift) break; i += 1; } end = i; while (i < height and self.oldnum[@intCast(i)] == new_index) { i += 1; } next_hunk = i; forward_limit = i; if (i >= height or @as(i64, @intCast(self.oldnum[@intCast(i)].?)) >= i) { forward_ref_limit = i; } else { forward_ref_limit = @as(i32, @intCast(self.oldnum[@intCast(i)].?)); } i = start - 1; // Grow back. if (shift < 0) { back_limit = back_ref_limit + (-shift); } while (i >= back_limit) { if (self.newhash[@intCast(i)] == self.oldhash[@intCast(i + shift)] or self.costEffective(@intCast(i + shift), @intCast(i), shift < 0)) { self.oldnum[@intCast(i)] = @intCast(i + shift); } else { break; } i -= 1; } i = end; // Grow forward. if (shift > 0) { forward_limit = forward_ref_limit - shift; } while (i < forward_limit) { if (self.newhash[@intCast(i)] == self.oldhash[@intCast(i + shift)] or self.costEffective(@intCast(i + shift), @intCast(i), shift > 0)) { self.oldnum[@intCast(i)] = @intCast(i + shift); } else { break; } i += 1; } back_limit = i; back_ref_limit = back_limit; if (shift > 0) { back_ref_limit += shift; } i = next_hunk; } } /// Whether moving line `from` to line `to` is cost effective. `blank` /// indicates whether the destination line would become blank. fn costEffective(self: *TerminalRenderer, from: i32, to: i32, blank: bool) bool { if (from == to) return false; const new_from: Size = self.oldnum[@intCast(from)] orelse @intCast(from); // On the left side of >= is the cost before moving, on the right // side -- cost after moving. // Cost before moving. var cost_before: i32 = 0; if (blank) { cost_before = @intCast(self.updateCostBlank(self.curbuf.?.line(@intCast(to)).?)); } else { cost_before = @intCast(self.updateCost(self.curbuf.?.line(@intCast(to)).?, self.curbuf.?.line(@intCast(to)).?)); } // Add cost of updating the source line. cost_before += @intCast(self.updateCost(self.curbuf.?.line(new_from).?, self.curbuf.?.line(@intCast(from)).?)); // Cost after moving. var cost_after: i32 = 0; if (@as(i32, @intCast(new_from)) == from) { // Source becomes blank after the move. cost_after = @intCast(self.updateCostBlank(self.curbuf.?.line(@intCast(from)).?)); } else { // Source gets updated from another line. cost_after = @intCast(self.updateCost(self.curbuf.?.line(new_from).?, self.curbuf.?.line(@intCast(from)).?)); } // Add cost of moving the source line to the destination. cost_after += @intCast(self.updateCost(self.curbuf.?.line(@intCast(from)).?, self.curbuf.?.line(@intCast(to)).?)); // Moving is cost effective when it doesn't cost more. return cost_before >= cost_after; } /// The cost of updating line `from` into line `to`. fn updateCost(self: *TerminalRenderer, from: *const Line, to: *const Line) usize { var cost: usize = 0; const width = self.curbuf.?.width(); var i: usize = width; var fidx: usize = 0; var tidx: usize = 0; while (i > 0) : ({ i -= 1; fidx += 1; tidx += 1; }) { if (!cellEqual(cellVal(from.at(@intCast(fidx))), cellVal(to.at(@intCast(tidx))))) { cost += 1; } } return cost; } /// The cost of updating line `to` to blank. fn updateCostBlank(self: *TerminalRenderer, to: *const Line) usize { const blank = self.clearBlank(); var cost: usize = 0; const width = self.curbuf.?.width(); var i: usize = width; var tidx: usize = 0; while (i > 0) : ({ i -= 1; tidx += 1; }) { if (!cellEqual(blank, cellVal(to.at(@intCast(tidx))))) { cost += 1; } } return cost; } /// Optimizes the screen to transform the old buffer into the new buffer /// using hard scrolls. fn scrollOptimize(self: *TerminalRenderer, newbuf: *RenderBuffer) !void { const height = newbuf.height(); if (self.oldnum.len < height) { self.allocator.free(self.oldnum); self.oldnum = try self.allocator.alloc(?Size, height); } try self.updateHashmap(newbuf); if (self.hashtab.len < height) return; // Pass 1 - from top to bottom scrolling up. { var i: i32 = 0; const h: i32 = @intCast(height); while (i < h) { while (i < h) { const v = self.oldnum[@intCast(i)]; if (v == new_index or @as(i64, @intCast(v.?)) <= i) { i += 1; } else break; } if (i >= h) break; const shift = @as(i32, @intCast(self.oldnum[@intCast(i)].?)) - i; // shift > 0 const start = i; i += 1; while (i < h) { const v = self.oldnum[@intCast(i)]; if (v == new_index or @as(i64, @intCast(v.?)) - i != shift) break; i += 1; } const end: i32 = i - 1 + shift; if (!try self.scrolln(newbuf, shift, start, end, h - 1)) continue; } } // Pass 2 - from bottom to top scrolling down. { const h: i32 = @intCast(height); var i: i32 = h - 1; while (i >= 0) { while (i >= 0) { const v = self.oldnum[@intCast(i)]; if (v == new_index or @as(i64, @intCast(v.?)) >= i) { i -= 1; } else break; } if (i < 0) break; const shift = @as(i32, @intCast(self.oldnum[@intCast(i)].?)) - i; // shift < 0 const end: i32 = i; i -= 1; while (i >= 0) { const v = self.oldnum[@intCast(i)]; if (v == new_index or @as(i64, @intCast(v.?)) - i != shift) break; i -= 1; } const start: i32 = i + 1 - (-shift); if (!try self.scrolln(newbuf, shift, start, end, h - 1)) continue; } } } /// Scrolls the screen up by `n` lines. fn scrolln(self: *TerminalRenderer, newbuf: *RenderBuffer, n: i32, top: i32, bot: i32, max_y: i32) !bool { const blank = self.clearBlank(); var ok: bool = undefined; if (n > 0) { ok = try self.scrollUp(newbuf, n, top, bot, 0, max_y, blank); if (!ok) { _ = try ir.ansi.setTopBottomMargins(&self.out.writer, @intCast(top + 1), @intCast(bot + 1)); self.cur.pos = null; self.at_phantom = false; ok = try self.scrollUp(newbuf, n, top, bot, top, bot, blank); _ = try ir.ansi.setTopBottomMargins(&self.out.writer, 1, @intCast(max_y + 1)); self.cur.pos = null; self.at_phantom = false; } if (!ok) { ok = try self.scrollIdl(newbuf, n, top, bot - n + 1, blank); } } else if (n < 0) { ok = try self.scrollDown(newbuf, -n, top, bot, 0, max_y, blank); if (!ok) { _ = try ir.ansi.setTopBottomMargins(&self.out.writer, @intCast(top + 1), @intCast(bot + 1)); self.cur.pos = null; self.at_phantom = false; ok = try self.scrollDown(newbuf, -n, top, bot, top, bot, blank); _ = try ir.ansi.setTopBottomMargins(&self.out.writer, 1, @intCast(max_y + 1)); self.cur.pos = null; self.at_phantom = false; if (!ok) { ok = try self.scrollIdl(newbuf, -n, bot + n + 1, top, blank); } } } else { return true; } if (!ok) return false; self.scrollBuffer(&self.curbuf.?, n, top, bot, blank); // Shift hash values too, they can be reused. self.scrollOldhash(n, top, bot); return true; } /// Scrolls the buffer by `n` lines. fn scrollBuffer(self: *TerminalRenderer, b: *RenderBuffer, n: i32, top_in: i32, bot_in: i32, blank: Cell) void { if (top_in < 0 or bot_in < top_in or bot_in >= @as(i32, @intCast(b.height()))) { // Nothing to scroll. return; } if (n < 0) { // Shift n lines downwards. const limit: i32 = top_in - n; var line: i32 = bot_in; while (line >= limit and line >= top_in) { if (b.line(@intCast(line))) |dst| { if (b.line(@intCast(line + n))) |src| { @memcpy(dst.cells, src.cells); } } line -= 1; } line = top_in; while (line < limit and line <= bot_in) : (line += 1) { b.fillArea(blank, .new(0, @intCast(line), b.width(), 1)); } } if (n > 0) { // Shift n lines upwards. const limit: i32 = bot_in - n; var line: i32 = top_in; while (line <= limit and line <= bot_in) : (line += 1) { if (b.line(@intCast(line))) |dst| { if (b.line(@intCast(line + n))) |src| { @memcpy(dst.cells, src.cells); } } } var l2: i32 = bot_in; while (l2 > limit and l2 >= top_in) { b.fillArea(blank, .new(0, @intCast(l2), b.width(), 1)); l2 -= 1; } } self.touchLine(b, top_in, bot_in - top_in + 1, true); } /// Marks `n` lines starting at `y` as touched (or untouched when /// `changed` is false). fn touchLine(self: *TerminalRenderer, newbuf: *RenderBuffer, y: i32, n: i32, changed: bool) void { _ = self; const height: i32 = @intCast(newbuf.height()); if (n < 0 or y < 0 or y >= height or newbuf.touched.len == 0 or newbuf.touched.len < newbuf.height()) { return; // Nothing to touch. } const width = newbuf.width(); var i = y; while (i < y + n and i < height) : (i += 1) { if (changed) { newbuf.touchLine(0, @intCast(i), width); } else { newbuf.touched[@intCast(i)] = .untouched; } } } /// Scrolls the screen up by `n` lines without changing the buffer. fn scrollUp(self: *TerminalRenderer, newbuf: *RenderBuffer, n: i32, top: i32, bot: i32, min_y: i32, max_y: i32, blank: Cell) !bool { if (n == 1 and top == min_y and bot == max_y) { try self.move(newbuf, 0, @intCast(bot)); try self.updatePen(blank); try self.out.writer.writeByte('\n'); } else if (n == 1 and bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); _ = try ir.ansi.deleteLine(&self.out.writer, 1); } else if (top == min_y and bot == max_y) { const supports_su = self.caps.su; try self.move(newbuf, 0, @intCast(bot)); try self.updatePen(blank); if (supports_su) { _ = try ir.ansi.scrollUp(&self.out.writer, @intCast(n)); } else { var i: i32 = 0; while (i < n) : (i += 1) try self.out.writer.writeByte('\n'); } } else if (bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); _ = try ir.ansi.deleteLine(&self.out.writer, @intCast(n)); } else { return false; } return true; } /// Scrolls the screen down by `n` lines without changing the buffer. fn scrollDown(self: *TerminalRenderer, newbuf: *RenderBuffer, n: i32, top: i32, bot: i32, min_y: i32, max_y: i32, blank: Cell) !bool { if (n == 1 and top == min_y and bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); try self.emitAll(ir.ansi.reverseIndex); } else if (n == 1 and bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); _ = try ir.ansi.insertLine(&self.out.writer, 1); } else if (top == min_y and bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); if (self.caps.sd) { _ = try ir.ansi.scrollDown(&self.out.writer, @intCast(n)); } else { var i: i32 = 0; while (i < n) : (i += 1) try self.emitAll(ir.ansi.reverseIndex); } } else if (bot == max_y) { try self.move(newbuf, 0, @intCast(top)); try self.updatePen(blank); _ = try ir.ansi.insertLine(&self.out.writer, @intCast(n)); } else { return false; } return true; } /// Scrolls the screen `n` lines using DL at `del` and IL at `ins`. fn scrollIdl(self: *TerminalRenderer, newbuf: *RenderBuffer, n: i32, del: i32, ins: i32, blank: Cell) !bool { if (n < 0) return false; // Delete lines. try self.move(newbuf, 0, @intCast(del)); try self.updatePen(blank); _ = try ir.ansi.deleteLine(&self.out.writer, @intCast(n)); // Insert lines. try self.move(newbuf, 0, @intCast(ins)); try self.updatePen(blank); _ = try ir.ansi.insertLine(&self.out.writer, @intCast(n)); return true; } // --- render ------------------------------------------------------------------- /// Renders the given buffer, queuing the minimal output needed to /// transition the terminal to the new state. Call `flush` afterwards. pub fn render(self: *TerminalRenderer, newbuf: *RenderBuffer) !void { // Do we need to render anything? const touched_lines = newbuf.touchedLines(); if (!self.clear and touched_lines == 0) return; if (self.curbuf == null or self.curbuf.?.bounds().empty()) { // Initialize the current buffer self.curbuf = try .init(self.allocator, newbuf.width(), newbuf.height()); } const new_width = newbuf.width(); const new_height = newbuf.height(); const cur_width = self.curbuf.?.width(); const cur_height = self.curbuf.?.height(); if (cur_width != new_width or cur_height != new_height) { self.allocator.free(self.oldhash); self.oldhash = &.{}; self.allocator.free(self.newhash); self.newhash = &.{}; // A shrink makes the terminal reflow in emulator-defined ways the // incremental model cannot predict; force a full repaint. Only in // fullscreen, where the renderer owns every cell it is about to // clear. Inline mode uses the narrower partial clear below. if (self.flags.fullscreen and (new_width < cur_width or new_height < cur_height)) { self.clear = true; } } const partial_clear = !self.flags.fullscreen and self.cur.pos != null and cur_width == new_width and cur_height > 0 and cur_height > new_height; if (!self.clear and partial_clear) { try self.clearBelow(newbuf, null, @intCast(new_height - 1)); } // Resize the model before diffing so the loop below walks every row // of the new screen, including rows added by a grow. if (cur_width != new_width or cur_height != new_height) { try self.curbuf.?.resize(new_width, new_height); } if (self.clear) { try self.clearUpdate(newbuf); self.clear = false; } else if (touched_lines > 0) { if (self.flags.scroll_optim and self.flags.fullscreen) { try self.scrollOptimize(newbuf); } var non_empty: usize = new_height; non_empty = try self.clearBottom(newbuf, non_empty); var i: usize = 0; while (i < non_empty) : (i += 1) { if (newbuf.touched.len == 0 or i >= newbuf.touched.len or newbuf.touched[i] == .changed) { try self.transformLine(newbuf, @intCast(i)); } // Mark line changed successfully. if (i < newbuf.touched.len and i < newbuf.height()) { newbuf.touched[i] = .synced; } if (i < self.curbuf.?.touched.len and i < self.curbuf.?.height()) { self.curbuf.?.touched[i] = .synced; } } } if (!self.flags.fullscreen and (cur_width != new_width or cur_height != new_height)) { try self.move(newbuf, 0, @intCast(new_height - 1)); } // Sync the touched tables. for (newbuf.touched) |*tab| { tab.* = .synced; } for (self.curbuf.?.touched) |*tab| { tab.* = .synced; } try self.updatePen(null); // nil indicates a blank cell with no styles } /// Terminal renderer flags. pub const Flags = packed struct { fullscreen: bool = false, relative_cursor: bool = false, map_newline: bool = false, scroll_optim: bool = false, grapheme_width: bool = false, }; /// ANSI control-sequence capabilities, keyed by terminal type via /// `xtermCaps`. Mirrors uv `capabilities`. pub const Caps = packed struct(u12) { vpa: bool = false, // Vertical Position Absolute hpa: bool = false, // Horizontal Position Absolute cha: bool = false, // Cursor Horizontal Absolute cht: bool = false, // Cursor Horizontal Tab cbt: bool = false, // Cursor Backward Tab rep: bool = false, // Repeat Previous Character ech: bool = false, // Erase Character ich: bool = false, // Insert Character sd: bool = false, // Scroll Down su: bool = false, // Scroll Up ht: bool = false, // Tabulation (tty-dependent) bs: bool = false, // Backspace (tty-dependent) pub fn contains(self: Caps, caps: Caps) bool { return (@as(u12, @bitCast(self)) & @as(u12, @bitCast(caps))) == @as(u12, @bitCast(caps)); } }; pub const no_caps: Caps = .{}; pub const all_caps: Caps = .{ .vpa = true, .hpa = true, .cha = true, .cht = true, .cbt = true, .rep = true, .ech = true, .ich = true, .sd = true, .su = true, }; /// The value used to indicate lines created by insertions and scrolls. const new_index: ?Size = null; /// A cursor position. `null` (in `Cursor.pos`) means "unknown" (forces an /// absolute move). const Pos = struct { x: Size = 0, y: Size = 0, }; /// The cursor model: the last written cell (pen) plus its position. A null /// `pos` means the position is unknown and an absolute move is required. const Cursor = struct { cell: Cell = .space, pos: ?Pos = null, }; /// Bit values of the `Style.attrs` mask (mirrors uv `AttrBold`, ...). const attrBold: u8 = 1 << 0; const attrFaint: u8 = 1 << 1; const attrItalic: u8 = 1 << 2; const attrBlink: u8 = 1 << 3; const attrRapidBlink: u8 = 1 << 4; /// One slot of the scroll-optimization hash table. Mirrors uv `hashmap`. const HashEntry = struct { value: u64 = 0, old_count: usize = 0, new_count: usize = 0, old_index: Size = 0, new_index: Size = 0, }; /// Sink builder for cursor-move sequence candidates. Candidates that don't /// fit are marked `overflow` and skipped (uv used unbounded builders). const Sink = struct { buf: []u8, len: usize = 0, overflow: bool = false, fn add(s: *Sink, data: []const u8) void { if (s.overflow or s.len > s.buf.len -| data.len) { s.overflow = true; return; } @memcpy(s.buf[s.len..][0..data.len], data); s.len += data.len; } fn addByte(s: *Sink, b: u8) void { s.add(&[1]u8{b}); } fn addNumber(s: *Sink, n: usize) void { var tmp: [20]u8 = undefined; s.add(std.fmt.bufPrint(&tmp, "{d}", .{n}) catch unreachable); } fn slice(s: *const Sink) []const u8 { return s.buf[0..s.len]; } }; // --- module-level helpers ------------------------------------------------------- /// The number of digits in a non-negative integer. fn numberLen(n: usize) usize { if (n < 10) return 1; if (n < 100) return 2; if (n < 1000) return 3; if (n < 10000) return 4; if (n < 100000) return 5; if (n < 10000000) return 7; return 9; } /// The number of bytes a CSI parameter sequence with final byte `final` emits /// for parameter `n` (mirrors `writeCsiParam`). fn csiParamLen(n: usize) usize { return 3 + (if (n > 1) numberLen(n) else 0); } /// The number of bytes a CSI position sequence emits for a 1-based position /// `n` (mirrors `writeCsiPos`). fn csiPosLen(n: usize) usize { return 3 + (if (n > 0) numberLen(n) else 0); } /// The number of bytes `cursorPosition` would emit for column x, row y. fn cupLen(x: usize, y: usize) usize { if (y <= 1 and x <= 1) return 3; return 2 + (if (y > 0) numberLen(y) else 0) + 1 + (if (x > 0) numberLen(x) else 0) + 1; } /// Whether the given cell can be erased by clear commands like EL. fn canClearWith(c: ?Cell) bool { if (c == null) return true; const cc = c.?; if (cc.width != 1 or cc.content.len != 1 or !std.mem.eql(u8, cc.content, " ")) return false; return cc.style.underline == .none and (@as(u8, @bitCast(cc.style.attrs)) & (~(attrBold | attrFaint | attrItalic | attrBlink | attrRapidBlink))) == 0 and cc.link.isZero(); } fn absI32(n: i32) i32 { return if (n < 0) -n else n; } /// Whether a cell is nil or a blank space with a clearable style. Mirrors /// `canClearWith` (bce terminfo capability assumed). fn canClearWithValue(c: ?*Cell) bool { return canClearWith(cellVal(c)); } /// Converts a grid cell pointer to an optional value copy. fn cellVal(p: ?*Cell) ?Cell { return if (p) |c| c.* else null; } /// Converts an optional cell value to an optional const pointer. The pointer /// is only valid within the enclosing statement. fn cref(c: ?Cell) ?*const Cell { return if (c) |v| &v else null; } /// Whether two cells are equal. A null cell is only equal to a null cell. /// Mirrors uv `cellEqual`. fn cellEqual(a: ?Cell, b: ?Cell) bool { if (a == null or b == null) return a == null and b == null; return a.?.equal(b.?); } /// Slices `count` cells off the front of a line. fn cutLine(line: Line, count: usize) Line { const n = @min(count, line.cells.len); return .{ .cells = line.cells[n..] }; } /// Copies `new` into `old` from the given index, mirroring Go's `copy` /// calls in `transformLine`. fn copyLineInto(old: *Line, new: *const Line, from: usize) void { if (from < old.cells.len and from < new.cells.len) { const n = @min(old.cells.len - from, new.cells.len - from); @memcpy(old.cells[from..][0..n], new.cells[from..][0..n]); } else { const n = @min(old.cells.len, new.cells.len); @memcpy(old.cells[0..n], new.cells[0..n]); } } /// Not "local" (short-distance) movement using the defined thresholds. fn notLocal(cols: i64, fx: i64, fy: i64, tx: i64, ty: i64) bool { const long_dist: i64 = 8 - 1; return (tx > long_dist) and (tx < cols - 1 - long_dist) and (absI64(ty - fy) + absI64(tx - fx) > long_dist); } fn absI64(n: i64) i64 { return if (n < 0) -n else n; } /// Returns the relative cursor movement sequence, writing it into `out`. /// Mirrors uv `relativeCursorMove`. fn relativeCursorMove( s: *TerminalRenderer, newbuf: ?*RenderBuffer, out: *Sink, fx_in: i32, fy: i32, tx: i32, ty: i32, overwrite_in: bool, use_tabs: bool, use_backspace: bool, ) void { var fx = fx_in; var overwrite = overwrite_in; if (newbuf == null) overwrite = false; // We can't overwrite the current buffer. if (ty != fy) { var yseq_len: usize = 0; var yseq_kind: enum { none, vpa, cud, cuu, newline, ri } = .none; if (s.caps.vpa and !s.flags.relative_cursor) { yseq_kind = .vpa; yseq_len = csiPosLen(@as(usize, @intCast(ty + 1))); } if (ty > fy) { const n: usize = @intCast(ty - fy); const cud_len = csiParamLen(n); if (yseq_len == 0 or cud_len < yseq_len) { yseq_kind = .cud; yseq_len = cud_len; } if (!s.flags.fullscreen or n < yseq_len) { // n is the cost of newline chars yseq_kind = .newline; if (s.flags.map_newline) { fx = 0; } } } else if (ty < fy) { const n: usize = @intCast(fy - ty); const cuu_len = csiParamLen(n); if (yseq_len == 0 or cuu_len < yseq_len) { yseq_kind = .cuu; yseq_len = cuu_len; } if (n == 1 and fy - 1 > 0) { yseq_kind = .ri; } } switch (yseq_kind) { .vpa => { out.add("\x1b["); if (ty + 1 > 0) out.addNumber(@intCast(ty + 1)); out.addByte('d'); }, .cud => { out.add("\x1b["); const n: usize = @intCast(ty - fy); if (n > 1) out.addNumber(n); out.addByte('B'); }, .cuu => { out.add("\x1b["); const n: usize = @intCast(fy - ty); if (n > 1) out.addNumber(n); out.addByte('A'); }, .newline => { const n: usize = @intCast(ty - fy); var k: usize = 0; while (k < n) : (k += 1) out.addByte('\n'); }, .ri => out.add("\x1bM"), .none => {}, } } if (tx != fx) { var xseq_len: usize = 0; var xseq_kind: enum { none, abs, cuf, cub, bs, ovw } = .none; if (!s.flags.relative_cursor) { if (s.caps.hpa) { xseq_kind = .abs; xseq_len = csiPosLen(@as(usize, @intCast(tx + 1))); } else if (s.caps.cha) { xseq_kind = .abs; xseq_len = csiPosLen(@as(usize, @intCast(tx + 1))); } } var ovw_buf: [512]u8 = undefined; var ovw_len: usize = 0; if (tx > fx) { var n: usize = @intCast(tx - fx); if (use_tabs and s.tabs != null and fx >= 0) { var tabs: usize = 0; var col: usize = @intCast(fx); while (true) { const nxt = s.tabs.?.next(col); if (nxt > @as(usize, @intCast(tx))) break; tabs += 1; if (col == nxt or col >= (s.tabs.?.width() -| 1)) break; col = nxt; } if (tabs > 0) { // CHT is disabled: uv disabled it because the linux // console and some terminals (e.g. Alacritty) don't // support it. var k: usize = 0; while (k < tabs) : (k += 1) out.addByte('\t'); fx = @intCast(col); n = @intCast(tx - fx); } } const cuf_len = csiParamLen(n); if (xseq_len == 0 or cuf_len < xseq_len) { xseq_kind = .cuf; xseq_len = cuf_len; } // If we have no attribute and style changes, overwrite is cheaper. if (overwrite and ty >= 0 and fx >= 0) { var i: i32 = 0; while (i < @as(i32, @intCast(n))) { const cell = newbuf.?.cellAt(@intCast(fx + i), @intCast(ty)); if (cell != null and cell.?.width > 0) { i += @as(i32, @intCast(cell.?.width - 1)); if (!cell.?.style.equal(s.cur.cell.style) or !cell.?.link.equal(s.cur.cell.link)) { overwrite = false; break; } } i += 1; } } if (overwrite and ty >= 0 and fx >= 0) { var sink = Sink{ .buf = &ovw_buf }; var i: i32 = 0; while (i < @as(i32, @intCast(n))) { const cell = newbuf.?.cellAt(@intCast(fx + i), @intCast(ty)); if (cell != null and cell.?.width > 0) { sink.add(cell.?.content); i += @as(i32, @intCast(cell.?.width - 1)); } i += 1; } if (!sink.overflow and sink.len < xseq_len) { xseq_kind = .ovw; xseq_len = sink.len; ovw_len = sink.len; } } } else { // tx < fx var n: usize = @intCast(fx - tx); if (use_tabs and s.tabs != null and s.caps.cbt) { // VT100 does not support backward tabs. var col: usize = @intCast(fx); var cbt: usize = 0; while (true) { const prev = s.tabs.?.prev(col); if (prev < @as(usize, @intCast(tx))) break; col = prev; cbt += 1; if (col == prev or col <= 0) break; } if (cbt > 0) { out.add("\x1b["); if (cbt > 1) out.addNumber(cbt); out.addByte('Z'); n = col - @as(usize, @intCast(tx)); } } const cub_len = csiParamLen(n); if (xseq_len == 0 or cub_len < xseq_len) { xseq_kind = .cub; xseq_len = cub_len; } if (use_backspace and n < xseq_len) { xseq_kind = .bs; } } switch (xseq_kind) { .abs => { out.add("\x1b["); if (tx + 1 > 0) out.addNumber(@intCast(tx + 1)); out.addByte('G'); }, .cuf => { const n: usize = @intCast(tx - fx); out.add("\x1b["); if (n > 1) out.addNumber(n); out.addByte('C'); }, .cub => { const n: usize = @intCast(fx - tx); out.add("\x1b["); if (n > 1) out.addNumber(n); out.addByte('D'); }, .bs => { const n: usize = @intCast(fx - tx); var k: usize = 0; while (k < n) : (k += 1) out.addByte(0x08); }, .ovw => { out.add(ovw_buf[0..ovw_len]); }, .none => {}, } } } /// Returns the control-sequence capabilities for the given terminal type. fn xtermCaps(term: []const u8) Caps { var parts = std.mem.splitScalar(u8, term, '-'); const first = parts.first(); if (first.len == 0) return .{}; if (std.mem.eql(u8, first, "contour") or std.mem.eql(u8, first, "foot") or std.mem.eql(u8, first, "ghostty") or std.mem.eql(u8, first, "kitty") or std.mem.eql(u8, first, "rio") or std.mem.eql(u8, first, "st") or std.mem.eql(u8, first, "tmux") or std.mem.eql(u8, first, "wezterm")) { return all_caps; } if (std.mem.eql(u8, first, "xterm")) { const second = parts.next(); if (second != null and (std.mem.eql(u8, second.?, "ghostty") or std.mem.eql(u8, second.?, "kitty") or std.mem.eql(u8, second.?, "rio"))) { return all_caps; } // NOTE: We exclude capHPA from allCaps because terminals like // Konsole don't support it. Xterm terminfo defines HPA as CHA. var v = all_caps; v.hpa = false; v.cht = false; v.rep = false; return v; } if (std.mem.eql(u8, first, "alacritty")) { var v = all_caps; v.cht = false; // alacritty added CHT support in 2024-12-28. return v; } if (std.mem.eql(u8, first, "screen")) { var v = all_caps; v.rep = false; return v; } if (std.mem.eql(u8, first, "linux")) { const v: Caps = .{ .vpa = true, .cha = true, .hpa = true, .ech = true, .ich = true, }; return v; } return .{}; } const t = std.testing; const lorem_ipsum_0 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at ornare risus, quis lacinia magna. Suspendisse egestas purus risus, id rutrum diam porta non. Duis luctus tempus dictum. Maecenas luctus metus vitae nulla consectetur egestas. Curabitur faucibus nunc vel eros semper scelerisque. Proin dictum aliquam lacus dignissim fringilla. Praesent ut quam id dui aliquam vehicula in vitae orci. Fusce imperdiet aliquam quam. Nullam euismod magna tincidunt nisl ullamcorper, dignissim rutrum arcu rutrum. Nulla ac fringilla velit. Duis non pellentesque erat."; // Ports uv's `TestRendererOutput` (terminal_renderer_output_test.go). Each // case renders a sequence of frames into a 10x5 screen and asserts the exact // bytes `flush`ed, so sequence costs and strategy choices must match x/ansi. test "renderer output parity with uv" { const Case = struct { input: []const []const u8, wrap: []const bool = &.{}, relative: bool = false, altscreen: bool = false, expected: []const []const u8, }; const l0 = lorem_ipsum_0; const cases = [_]Case{ .{ .input = &.{ "ABC", "XXX" }, .relative = true, .expected = &.{ "\rABC", "\rXXX" }, }, .{ .input = &.{ l0, l0[10..] }, .wrap = &.{ true, true }, .altscreen = true, .expected = &.{ "\x1b[H\x1b[2JLorem ipsu\r\nm dolor si\r\nt amet, co\r\nnsectetur\r\nadipiscin\x1b[?7lg\x1b[?7h", "\r\n elit. Vi\x1b[?7lv\x1b[?7h", }, }, .{ .input = &.{ l0, l0[20..] }, .wrap = &.{ true, true }, .altscreen = true, .expected = &.{ "\x1b[H\x1b[2JLorem ipsu\r\nm dolor si\r\nt amet, co\r\nnsectetur\r\nadipiscin\x1b[?7lg\x1b[?7h", "\r\x1b[2S\x1bM elit. Viv\r\namus at o\x1b[?7lr\x1b[?7h", }, }, .{ .input = &.{ "ABC\nDEF\nGHI\n", "ABC\n\nDEF\nGHI" }, .wrap = &.{ true, true }, .altscreen = true, .expected = &.{ "\x1b[H\x1b[2JABC\r\nDEF\r\nGHI", "\r\x1bM\x1b[L", }, }, .{ .input = &.{ "\nABCEFGHIJK", "\nABCE " }, .expected = &.{ "\x1b[2;1HABCEFGHIJK", "\r\x1b[5G\x1b[K", }, }, }; for (cases) |c| { var sink_buf: [16 * 1024]u8 = undefined; var tr: TerminalRenderer = .init(t.allocator, .fixed(&sink_buf), "xterm-256color"); defer tr.deinit(); tr.setScrollOptim(true); tr.setFullscreen(c.altscreen); tr.setRelativeCursor(c.relative); if (c.altscreen) { tr.saveCursor(); tr.erase(); } var screen: Screen = try .init(t.allocator, 10, 5); defer screen.deinit(); for (c.input, 0..) |input, i| { var comp: styled.String = .new(input); if (i < c.wrap.len) comp.wrap = c.wrap[i]; try comp.draw(t.allocator, &screen, screen.render_buffer.bounds()); tr.sink = .fixed(&sink_buf); try tr.render(&screen.render_buffer); try tr.flush(); try t.expectEqualStrings(c.expected[i], tr.sink.buffered()); } } } // Ports uv's `TestRendererWideCellReanchor`: a line with wide cells must be // re-anchored with a single CHA after the move (wcwidth mode), and must not // re-anchor at all in grapheme mode. test "renderer wide cell reanchor parity" { const Counts = struct { wc_reanchor: usize = 0, wc_per_cell: usize = 0, grapheme_reanchor: usize = 0, }; const go = struct { fn renderCounts(allocator: Allocator) !Counts { var result = Counts{}; inline for ([_]bool{ false, true }) |grapheme| { var sink_buf: [16 * 1024]u8 = undefined; var tr: TerminalRenderer = .init(allocator, .fixed(&sink_buf), "xterm-256color"); defer tr.deinit(); tr.setFullscreen(true); tr.setGraphemeWidth(grapheme); tr.saveCursor(); tr.erase(); var screen: Screen = try .init(allocator, 10, 1); defer screen.deinit(); screen.method = if (grapheme) .grapheme else .wcwidth; const comp: styled.String = .new("世界"); try comp.draw(allocator, &screen, screen.render_buffer.bounds()); try tr.render(&screen.render_buffer); try tr.flush(); const out = tr.sink.buffered(); if (grapheme) { result.grapheme_reanchor = std.mem.count(u8, out, "\x1b[5G"); } else { result.wc_reanchor = std.mem.count(u8, out, "\x1b[5G"); result.wc_per_cell = std.mem.count(u8, out, "\x1b[3G"); } } return result; } }.renderCounts; const r = try go(t.allocator); try t.expectEqual(1, r.wc_reanchor); try t.expectEqual(0, r.wc_per_cell); try t.expectEqual(0, r.grapheme_reanchor); } test "fuzz renderer" { try t.fuzz({}, fuzzRenderer, .{ .corpus = &.{}, }); } fn fuzzRenderer(_: void, smith: *t.Smith) anyerror!void { const width: usize = smith.valueRangeAtMost(u16, 1, 16); const height: usize = smith.valueRangeAtMost(u16, 1, 16); var sink_buf: [16 * 1024]u8 = undefined; var tr: ir.TerminalRenderer = .init(t.allocator, .fixed(&sink_buf), "xterm-256color"); defer tr.deinit(); tr.setFullscreen(smith.value(bool)); tr.setRelativeCursor(smith.value(bool)); tr.setScrollOptim(smith.value(bool)); tr.setGraphemeWidth(smith.value(bool)); tr.setBackspace(smith.value(bool)); if (smith.value(bool)) tr.setTabStops(width) catch {}; if (smith.value(bool)) { tr.saveCursor(); tr.erase(); } var screen: ir.Screen = try .init(t.allocator, @intCast(width), @intCast(height)); defer screen.deinit(); screen.method = if (smith.value(bool)) .grapheme else .wcwidth; const rounds: usize = 1 + @as(usize, smith.index(4)); var round: usize = 0; while (round < rounds) : (round += 1) { var mut: usize = 0; while (!smith.eos() and mut < 8) : (mut += 1) { const y = smith.index(height); const x = smith.index(width); const xs: Size = @intCast(x); const ys: Size = @intCast(y); switch (smith.value(u3)) { 0 => screen.setCell(xs, ys, null), 1 => screen.setCell(xs, ys, .space), 2 => { var cbuf: [8]u8 = undefined; const clen = smith.slice(&cbuf); screen.setCell(xs, ys, .of(cbuf[0..clen], @intCast(1))); }, 3 => screen.setCell(xs, ys, .of("世", 2)), 4 => screen.setCell(xs, ys, .of("a", 1)), 5 => screen.render_buffer.touchLine(0, ys, screen.render_buffer.width()), 6 => screen.render_buffer.clear(), 7 => screen.render_buffer.fill(.space), } } tr.sink = .fixed(&sink_buf); tr.render(&screen.render_buffer) catch |err| switch (err) { // The failing test allocator and the fixed-size sink both // legitimately reject work under fuzzing; skip such rounds. error.OutOfMemory => return, else => continue, }; try tr.flush(); } }