//! Cell buffer primitives: `Line`, `Lines`, `Buffer`, and `RenderBuffer`. //! //! Port of ultraviolet's `buffer.go`. A `Line` is a row of `Cell`s; a `Buffer` //! is a grid of lines. `RenderBuffer` wraps a `Buffer` plus a per-line //! `Touched` table of `LineData` used by the renderer to emit only the changed //! cells: `.untouched`, `.synced`, or `.changed` with a half-open span //! `{ first_cell, last_cell }` covering `[first, last)`. The renderer (Phase 7) //! flips rewritten lines to `.synced`. const std = @import("std"); const ir = @import("root.zig"); const t = std.testing; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Writer = std.Io.Writer; const Line = ir.Line; const Rectangle = ir.Rectangle; const Cell = ir.Cell; const RenderBuffer = ir.RenderBuffer; const Lines = ir.Lines; const Buffer = @This(); const Size = ir.Size; allocator: Allocator, lines: []Line = &.{}, pub fn init(allocator: Allocator, w: Size, h: Size) !Buffer { var b = Buffer{ .allocator = allocator }; errdefer b.deinit(); try b.resize(w, h); return b; } pub fn deinit(self: *Buffer) void { for (self.lines) |l| self.allocator.free(l.cells); self.allocator.free(self.lines); } pub fn width(self: Buffer) Size { if (self.lines.len == 0) return 0; return self.lines[0].width(); } pub fn height(self: Buffer) Size { return @intCast(self.lines.len); } pub fn bounds(self: Buffer) Rectangle { return .new(0, 0, self.width(), self.height()); } pub fn line(self: *Buffer, y: Size) ?*Line { if (y >= self.lines.len) return null; return &self.lines[y]; } pub fn cellAt(self: *Buffer, x: Size, y: Size) ?*Cell { const l = self.line(y) orelse return null; return l.at(x); } pub fn setCell(self: *Buffer, x: Size, y: Size, c: ?Cell) void { const l = self.line(y) orelse return; l.set(x, c); } pub fn resize(self: *Buffer, new_width: Size, new_height: Size) !void { const cur_width = self.width(); const cur_height = self.height(); if (cur_width == new_width and cur_height == new_height) return; if (new_width > cur_width) { for (self.lines) |*l| { const old_len = l.cells.len; l.cells = try self.allocator.realloc(l.cells, new_width); for (l.cells[old_len..]) |*c| c.* = .space; } } else if (new_width < cur_width) { for (self.lines) |*l| { l.cells = try self.allocator.realloc(l.cells, new_width); } } if (new_height > cur_height) { const old_len = self.lines.len; self.lines = try self.allocator.realloc(self.lines, new_height); for (self.lines[old_len..]) |*l| { l.* = try .init(self.allocator, new_width); } } else if (new_height < cur_height) { for (self.lines[new_height..]) |l| self.allocator.free(l.cells); self.lines = try self.allocator.realloc(self.lines, new_height); } } pub fn fill(self: *Buffer, cell: ?Cell) void { self.fillArea(cell, self.bounds()); } pub fn fillArea(self: *Buffer, cell: ?Cell, area: Rectangle) void { var cell_width: Size = 1; if (cell) |cc| { if (cc.width > 1) cell_width = cc.width; } var y = area.min_y; while (y < area.max_y) : (y += 1) { var x = area.min_x; while (x < area.max_x) : (x += cell_width) { self.setCell(x, y, cell); } } } pub fn clear(self: *Buffer) void { for (self.lines) |*buf_line| { for (buf_line.cells) |*cell| cell.* = .space; } } pub fn clearArea(self: *Buffer, area: Rectangle) void { self.fillArea(null, area); } pub fn cloneArea(self: *Buffer, area: Rectangle) !?Buffer { if (!area.inside(self.bounds())) return null; var buffer: Buffer = try .init(self.allocator, area.width(), area.height()); errdefer buffer.deinit(); var y = area.min_y; while (y < area.max_y) : (y += 1) { var x = area.min_x; while (x < area.max_x) { const p = self.cellAt(x, y) orelse { x += 1; continue; }; const c = p.*; if (c.isWidePlaceholder()) { x += 1; continue; } buffer.setCell(x - area.min_x, y - area.min_y, c); x += @max(c.width, 1); } } return buffer; } pub fn clone(self: *Buffer) !Buffer { return (try self.cloneArea(self.bounds())) orelse error.UnexpectedNull; } /// Draws the buffer onto the given screen (duck-typed: needs `bounds()` /// returning a `Rect` and `setCell(x, y, Cell)`). pub fn draw(self: *Buffer, screen: anytype, area: Rectangle) void { if (area.empty()) return; const b = screen.bounds(); if (!area.overlaps(b)) return; var y = area.min_y; while (y < area.max_y) : (y += 1) { var x = area.min_x; while (x < area.max_x) { const p = self.cellAt(x - area.min_x, y - area.min_y) orelse { x += 1; continue; }; const c = p.*; if (c.isWidePlaceholder()) { x += 1; continue; } screen.setCell(x, y, c); var w: Size = c.width; if (w == 0) w = 1; x += w; } } } pub fn insertLineArea(self: *Buffer, y: Size, n: Size, cell: ?Cell, area: Rectangle) void { if (n == 0 or y < area.min_y or y >= area.max_y or y >= self.height()) return; var nn = n; if (y + nn > area.max_y) nn = area.max_y - y; // Move existing lines down within the bounds. var i: usize = area.max_y; while (i > y + nn) { i -= 1; @memcpy(self.lines[i].cells[area.min_x..area.max_x], self.lines[i - nn].cells[area.min_x..area.max_x]); } // Clear the newly inserted lines within bounds. var j = y; while (j < y + nn) : (j += 1) { var x = area.min_x; while (x < area.max_x) : (x += 1) { self.setCell(x, j, cell); } } } pub fn deleteLineArea(self: *Buffer, y: Size, n: Size, cell: ?Cell, area: Rectangle) void { if (n == 0 or y < area.min_y or y >= area.max_y or y >= self.height()) return; var nn = n; if (nn > area.max_y - y) nn = area.max_y - y; // Shift cells up within the bounds. var dst: usize = y; while (dst < area.max_y - nn) : (dst += 1) { @memcpy(self.lines[dst].cells[area.min_x..area.max_x], self.lines[dst + nn].cells[area.min_x..area.max_x]); } // Fill the bottom n lines with blank cells. var i = area.max_y - nn; while (i < area.max_y) : (i += 1) { var x = area.min_x; while (x < area.max_x) : (x += 1) { self.setCell(x, i, cell); } } } pub fn insertCellArea(self: *Buffer, x: Size, y: Size, n: Size, cell: ?Cell, area: Rectangle) void { if (n == 0 or y < area.min_y or y >= area.max_y or y >= self.height() or x < area.min_x or x >= area.max_x or x >= self.width()) return; var nn = n; if (x + nn > area.max_x) nn = area.max_x - x; // Move existing cells within rectangle bounds to the right. var i: usize = area.max_x; while (i > x + nn) { i -= 1; self.lines[y].cells[i] = self.lines[y].cells[i - nn]; } // Clear the newly inserted cells within rectangle bounds. var j = x; while (j < x + nn) : (j += 1) { self.setCell(j, y, cell); } } pub fn deleteCellArea(self: *Buffer, x: Size, y: Size, n: Size, cell: ?Cell, area: Rectangle) void { if (n == 0 or y < area.min_y or y >= area.max_y or y >= self.height() or x < area.min_x or x >= area.max_x or x >= self.width()) return; var nn = n; const remaining = area.max_x - x; if (nn > remaining) nn = remaining; // Shift the remaining cells to the left, blanking wide cells via SetCell. var i: usize = x; while (i < area.max_x - nn) : (i += 1) { const src = self.cellAt(@intCast(i + nn), y) orelse continue; self.setCell(@intCast(i), y, src.*); } // Fill the vacated positions with the given cell. var j = area.max_x - nn; while (j < area.max_x) : (j += 1) { self.setCell(j, y, cell); } } pub fn string(self: *Buffer, allocator: Allocator) ![]u8 { return Lines.init(self.lines).string(allocator); } pub fn render(self: *Buffer, allocator: Allocator) ![]u8 { return Lines.init(self.lines).render(allocator); } /// A point/position (origin top-left). pub const Pos = struct { x: Size = 0, y: Size = 0, }; // // /// Renders a single line with the required SGR attributes and hyperlinks. // /// Empty (space) cells are emitted as spaces without styling; trailing spaces // /// are preserved (unlike `Line.string`). // fn renderLine(writer: *Writer, line: Line) Writer.Error!void { // var pen = Style{}; // var link = Link{}; // // for (line.cells) |cell| { // if (cell.isWidePlaceholder()) continue; // // if (cell.equal(.blank)) { // if (!pen.isZero()) { // try writer.writeAll(ansi.resetStyle); // pen = .{}; // } // if (!link.isZero()) { // _ = try ansi.resetHyperlink(writer, ""); // link = .{}; // } // try writer.writeAll(" "); // continue; // } // // if (cell.style.isZero() and !pen.isZero()) { // try writer.writeAll(ansi.resetStyle); // pen = .{}; // } // if (!cell.style.equal(pen)) { // _ = try Style.writeDiff(pen, cell.style, writer); // pen = cell.style; // } // // // Reset a stale hyperlink before switching. // if (!cell.link.equal(link) and link.url.len != 0) { // _ = try ansi.resetHyperlink(writer, ""); // link = .{}; // } // if (!cell.link.equal(link)) { // _ = try ansi.setHyperlink(writer, cell.link.url, cell.link.params); // link = cell.link; // } // // try writer.writeAll(cell.content); // } // // if (link.url.len != 0) _ = try ansi.resetHyperlink(writer, ""); // if (!pen.isZero()) try writer.writeAll(ansi.resetStyle); // } /// Trims trailing spaces from the end of each line, preserving any trailing /// `\r`. Mirrors uv `TrimSpace`. pub fn trimSpace(allocator: Allocator, slice: []const u8) ![]u8 { var out: ArrayList(u8) = .empty; defer out.deinit(allocator); var first = true; var splitter = std.mem.splitScalar(u8, slice, '\n'); while (splitter.next()) |l| { if (!first) try out.append(allocator, '\n'); first = false; var end = l.len; const has_cr = end != 0 and l[end - 1] == '\r'; if (has_cr) end -= 1; while (end != 0 and l[end - 1] == ' ') end -= 1; try out.appendSlice(allocator, l[0..end]); if (has_cr) try out.append(allocator, '\r'); } return out.toOwnedSlice(allocator); } test "buffer fill clear and resize" { var buffer: Buffer = try .init(t.allocator, 4, 3); defer buffer.deinit(); try t.expect(buffer.width() == 4); try t.expect(buffer.height() == 3); // try testing.expectEqual(@as(usize, 4), b.width()); // try testing.expectEqual(@as(usize, 3), b.height()); buffer.fill(.of("x", 1)); try t.expectEqualStrings("x", buffer.cellAt(2, 2).?.content); buffer.clear(); try t.expect(buffer.cellAt(2, 2).?.equal(.space)); try buffer.resize(6, 5); try t.expect(buffer.width() == 6); try t.expect(buffer.height() == 5); // try testing.expectEqual(@as(usize, 6), b.width()); // try testing.expectEqual(@as(usize, 5), b.height()); try t.expect(buffer.cellAt(5, 4).?.equal(.space)); try buffer.resize(2, 1); try t.expect(buffer.width() == 2); try t.expect(buffer.height() == 1); // try testing.expectEqual(@as(usize, 2), b.width()); // try testing.expectEqual(@as(usize, 1), b.height()); } test "trimSpace preserves CR and trims trailing spaces" { const slice = try trimSpace(t.allocator, "hello \r\nworld \n"); defer t.allocator.free(slice); try t.expectEqualStrings("hello\r\nworld\n", slice); } test "fuzz trim" { try t.fuzz({}, fuzzTrim, .{ .corpus = &.{ "", "hello ", " spaced out \t", "line1 \r\nline2 \n line3", " \r", "\r\r\n \n", " ", }, }); } fn fuzzTrim(_: void, smith: *t.Smith) anyerror!void { var buf: [256]u8 = undefined; const len = smith.slice(&buf); var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); const out = trimSpace(arena.allocator(), buf[0..len]) catch return; _ = out; } test "buffer line insert and delete" { var buffer: Buffer = try .init(t.allocator, 3, 3); defer buffer.deinit(); buffer.lines[0].cells[0] = .of("a", 1); buffer.lines[1].cells[1] = .of("b", 1); buffer.lines[2].cells[2] = .of("c", 1); // Insert line 0: rows shift down, top row cleared. buffer.insertLineArea(0, 1, null, buffer.bounds()); try t.expect(buffer.lines[0].cells[0].equal(.space)); // cleared top try t.expectEqualStrings("a", buffer.lines[1].cells[0].content); // old row 0 try t.expectEqualStrings("b", buffer.lines[2].cells[1].content); // old row 1 // Delete line 1: rows shift up, bottom row cleared. buffer.deleteLineArea(1, 1, null, buffer.bounds()); try t.expectEqualStrings("b", buffer.lines[1].cells[1].content); // old row 2 try t.expect(buffer.lines[2].cells[1].equal(.space)); // cleared bottom }