//! A stateful drawing surface: a [`screen.Screen`] plus a style/link/position //! cursor, mirroring uv's `screen/context.go`. //! //! Named departures from upstream, to be recorded in `Brain.md`: //! - Cluster segmentation uses `[styled.firstGraphemeCluster]` (infrared's own //! best-effort decoder, Brain decision #5) rather than uax29, keeping drawing //! consistent with `StyledString`. //! - `SetURL` takes its params already `:`-joined (uv joins a variadic slice //! into a fresh Go string). //! - `Print`/`Println`/`Printf` take a comptime Zig format string (uv boxes //! the arguments with `fmt`). //! - The context owns an allocator (given to `init`), and every cluster and //! link is copied into allocator-owned memory before it lands in a cell, so //! cells never borrow transient buffers (uv keeps its cell contents alive //! with a copying GC). Destroy the allocator (e.g. an arena) to free them; //! a cell overwritten before that leaks its copy. //! //! The context borrows the screen for its whole lifetime: `init` takes a //! pointer to the concrete screen's embedded `screen` field (the interface), //! e.g. `Context.init(&buffer.screen, arena.allocator())`. const std = @import("std"); const ir = @import("root.zig"); const scr = @import("screen.zig"); const Allocator = std.mem.Allocator; const t = std.testing; const Cell = ir.Cell; const Link = ir.Link; const Pos = scr.Pos; const Screen = scr.Screen; const Size = ir.Size; const Style = ir.Style; /// A drawing context over `scr` (uv `Context`). pub const Context = struct { scr: *Screen, allocator: Allocator, style: Style = .{}, link: Link = .{}, pos: Pos = .{}, /// Creates a context drawing on `screen` that dups clusters/links with /// `allocator`, reset to defaults. pub fn init(screen: *Screen, allocator: Allocator) Context { var c: Context = .{ .scr = screen, .allocator = allocator }; c.reset(); return c; } /// Resets the context to its default state. pub fn reset(self: *Context) void { self.style = .{}; self.link = .{}; self.pos = .{}; } pub fn setStyle(self: *Context, style: Style) void { self.style = style; } pub fn withStyle(self: Context, style: Style) Context { var c = self; c.setStyle(style); return c; } pub fn setLink(self: *Context, link: Link) void { self.link = link; } pub fn withLink(self: Context, link: Link) Context { var c = self; c.setLink(link); return c; } /// Sets the attribute bitmask (see `Style.read`). pub fn setAttrs(self: *Context, attrs: u8) void { self.style.attrs = @bitCast(attrs); } pub fn withAttrs(self: Context, attrs: u8) Context { var c = self; c.setAttrs(attrs); return c; } pub fn setBackground(self: *Context, bg: ?ir.Color) void { self.style.bg = if (bg) |col| Cell.optColor(col) else null; } pub fn withBackground(self: Context, bg: ?ir.Color) Context { var c = self; c.setBackground(bg); return c; } pub fn setForeground(self: *Context, fg: ?ir.Color) void { self.style.fg = if (fg) |col| Cell.optColor(col) else null; } pub fn withForeground(self: Context, fg: ?ir.Color) Context { var c = self; c.setForeground(fg); return c; } pub fn setUnderlineColor(self: *Context, color: ?ir.Color) void { self.style.underline_color = if (color) |col| Cell.optColor(col) else null; } pub fn withUnderlineColor(self: Context, color: ?ir.Color) Context { var c = self; c.setUnderlineColor(color); return c; } pub fn setUnderlineStyle(self: *Context, u: Style.Underline) void { self.style.underline = u; } pub fn withUnderlineStyle(self: Context, u: Style.Underline) Context { var c = self; c.setUnderlineStyle(u); return c; } /// Convenience: equals `setUnderlineStyle` with `.single`/`.none`. pub fn setUnderline(self: *Context, underline: bool) void { self.style.underline = if (underline) .single else .none; } pub fn withUnderline(self: Context, underline: bool) Context { var c = self; c.setUnderline(underline); return c; } /// Sets a boolean attribute on the context's style. pub fn setBold(self: *Context, bold: bool) void { self.style.attrs.bold = bold; } pub fn withBold(self: Context, bold: bool) Context { var c = self; c.setBold(bold); return c; } pub fn setItalic(self: *Context, italic: bool) void { self.style.attrs.italic = italic; } pub fn withItalic(self: Context, italic: bool) Context { var c = self; c.setItalic(italic); return c; } pub fn setStrikethrough(self: *Context, strikethrough: bool) void { self.style.attrs.strikethrough = strikethrough; } pub fn withStrikethrough(self: Context, strikethrough: bool) Context { var c = self; c.setStrikethrough(strikethrough); return c; } pub fn setFaint(self: *Context, faint: bool) void { self.style.attrs.faint = faint; } pub fn withFaint(self: Context, faint: bool) Context { var c = self; c.setFaint(faint); return c; } pub fn setBlink(self: *Context, blink: bool) void { self.style.attrs.blink = blink; } pub fn withBlink(self: Context, blink: bool) Context { var c = self; c.setBlink(blink); return c; } pub fn setReverse(self: *Context, reverse: bool) void { self.style.attrs.reverse = reverse; } pub fn withReverse(self: Context, reverse: bool) Context { var c = self; c.setReverse(reverse); return c; } pub fn setConceal(self: *Context, conceal: bool) void { self.style.attrs.conceal = conceal; } pub fn withConceal(self: Context, conceal: bool) Context { var c = self; c.setConceal(conceal); return c; } /// Sets the hyperlink; use an empty `url` to reset. `params` must already /// be `:`-joined (uv joins its variadic params itself). Cells copy the /// url/params into allocator-owned memory when the link is non-empty. pub fn setURL(self: *Context, url: []const u8, params: []const u8) void { if (url.len == 0) { self.link = .{}; return; } self.link = .{ .url = url, .params = params }; } pub fn withURL(self: Context, url: []const u8, params: []const u8) Context { var c = self; c.setURL(url, params); return c; } /// The current position (screen-local coordinates). pub fn position(self: *const Context) Pos { return self.pos; } /// Moves the cursor. Alias for [`moveTo`](Context.moveTo). pub fn setPosition(self: *Context, x: Size, y: Size) void { self.moveTo(x, y); } pub fn withPosition(self: Context, x: Size, y: Size) Context { var c = self; c.moveTo(x, y); return c; } /// Moves the cursor to the given coordinates. pub fn moveTo(self: *Context, x: Size, y: Size) void { self.pos = .{ .x = x, .y = y }; } /// Formats `args` per `fmt` and draws at the current position, advancing /// the cursor. Returns bytes of formatted output. The formatted buffer is /// transient; cells hold their own copies. pub fn print(self: *Context, comptime fmt: []const u8, args: anytype) !usize { const s = try std.fmt.allocPrint(self.allocator, fmt, args); defer self.allocator.free(s); return self.writeString(s); } /// `print` followed by a newline. pub fn println(self: *Context, comptime fmt: []const u8, args: anytype) !usize { const s = try std.fmt.allocPrint(self.allocator, fmt ++ "\n", args); defer self.allocator.free(s); return self.writeString(s); } /// `print` under its uv name (`printf`). pub fn printf(self: *Context, comptime fmt: []const u8, args: anytype) !usize { return self.print(fmt, args); } /// Draws `s` at `(x, y)` with the current style and link, cropping at the /// screen edge. The cursor is not moved. pub fn drawString(self: *Context, s: []const u8, x: Size, y: Size) !void { _ = try drawStringAt(self.scr, self.allocator, s, x, y, self.style, self.link, false); } /// Like [`drawString`](Context.drawString) but wraps at the screen edge. pub fn drawStringWrapped(self: *Context, s: []const u8, x: Size, y: Size) !void { _ = try drawStringAt(self.scr, self.allocator, s, x, y, self.style, self.link, true); } /// Writes `bytes` at the current position (wrapping), advancing the /// cursor. Returns the number of bytes consumed. pub fn write(self: *Context, bytes: []const u8) !usize { self.pos = try drawStringAt(self.scr, self.allocator, bytes, self.pos.x, self.pos.y, self.style, self.link, true); return bytes.len; } /// Writes `s` at the current position (wrapping), advancing the cursor. /// Returns the number of bytes consumed. pub fn writeString(self: *Context, s: []const u8) !usize { self.pos = try drawStringAt(self.scr, self.allocator, s, self.pos.x, self.pos.y, self.style, self.link, true); return s.len; } }; /// Iterates grapheme clusters with `styled.firstGraphemeCluster`, the same /// segmenter `StyledString` uses. const ClusterIter = struct { rest: []const u8, fn next(self: *ClusterIter) ?[]const u8 { if (self.rest.len == 0) return null; const gr = ir.styled.firstGraphemeCluster(self.rest); self.rest = self.rest[gr.len..]; return gr; } }; fn posIn(x: usize, y: usize, bounds: ir.Rectangle) bool { return x >= bounds.min_x and x < bounds.max_x and y >= bounds.min_y and y < bounds.max_y; } /// Draws `s` at `(x, y)`, mirroring uv's `drawStringAt` (context.go): the /// bounds are normalized to origin, clusters outside the screen are skipped, /// `'\n'` starts a new line, and with `wrap` clusters that do not fit move to /// the next line. When not wrapping, drawing stops at the right edge. Returns /// the updated position. /// /// Each drawn cluster (and the link url/params, once per call when set) is /// copied into `allocator`-owned memory so cells never borrow `s`. fn drawStringAt(screen: *Screen, allocator: Allocator, s: []const u8, x: Size, y: Size, style: Style, link: Link, wrap: bool) !Pos { var bounds = screen.bounds(); bounds.max_x -= bounds.min_x; bounds.max_y -= bounds.min_y; bounds.min_x = 0; bounds.min_y = 0; var screens_link = link; if (link.url.len > 0) { screens_link.url = try allocator.dupe(u8, link.url); screens_link.params = try allocator.dupe(u8, link.params); } var x_: usize = x; var y_: usize = y; if (!posIn(x_, y_, bounds)) return .{ .x = @intCast(x_), .y = @intCast(y_) }; const m = screen.widthMethod(); var it = ClusterIter{ .rest = s }; while (it.next()) |gr| { if (std.mem.eql(u8, gr, "\n")) { x_ = bounds.min_x; y_ += 1; continue; } const w = ir.width.stringWidth(m, gr); if (x_ + w > bounds.max_x) { if (wrap) { x_ = bounds.min_x; y_ += 1; } else { break; } } if (!posIn(x_, y_, bounds)) break; screen.setCell(@intCast(x_), @intCast(y_), .{ .content = try allocator.dupe(u8, gr), .style = style, .link = screens_link, .width = @intCast(@min(w, 255)), }); x_ += w; if (wrap and x_ >= bounds.max_x) { x_ = bounds.min_x; y_ += 1; } } return .{ .x = @intCast(x_), .y = @intCast(y_) }; } test "context drawString writes styled cells" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); var buf: ir.Screen = try .init(t.allocator, 8, 2); defer buf.deinit(); var ctx = Context.init(&buf.screen, arena.allocator()); ctx.setBold(true); ctx.setForeground(.red); try ctx.drawString("Hi", 0, 0); try t.expectEqualStrings("H", buf.screen.cellAt(0, 0).?.content); try t.expect(buf.screen.cellAt(0, 0).?.style.attrs.bold); try t.expect(buf.screen.cellAt(0, 0).?.style.attrs.italic == false); try t.expectEqual(ir.Color.red, buf.screen.cellAt(0, 0).?.style.fg.?); try t.expectEqualStrings("i", buf.screen.cellAt(1, 0).?.content); // Position is not advanced by drawString. try t.expectEqual(Pos{ .x = 0, .y = 0 }, ctx.position()); } test "context drawString handles newlines and clips at right edge" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); var buf: ir.Screen = try .init(t.allocator, 4, 2); defer buf.deinit(); var ctx = Context.init(&buf.screen, arena.allocator()); try ctx.drawString("ab\ncd", 0, 0); try t.expectEqualStrings("a", buf.screen.cellAt(0, 0).?.content); try t.expectEqualStrings("b", buf.screen.cellAt(1, 0).?.content); try t.expectEqualStrings("c", buf.screen.cellAt(0, 1).?.content); try t.expectEqualStrings("d", buf.screen.cellAt(1, 1).?.content); // Non-wrapping drawString crops at the right edge. try ctx.drawString("efgh", 2, 0); try t.expectEqualStrings("e", buf.screen.cellAt(2, 0).?.content); try t.expectEqualStrings("f", buf.screen.cellAt(3, 0).?.content); try t.expectEqualStrings("c", buf.screen.cellAt(0, 1).?.content); } test "context write wraps at the screen edge" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); var buf: ir.Screen = try .init(t.allocator, 4, 3); defer buf.deinit(); var ctx = Context.init(&buf.screen, arena.allocator()); const n = try ctx.write("abcdef"); try t.expectEqual(6, n); try t.expectEqualStrings("a", buf.screen.cellAt(0, 0).?.content); try t.expectEqualStrings("b", buf.screen.cellAt(1, 0).?.content); try t.expectEqualStrings("c", buf.screen.cellAt(2, 0).?.content); try t.expectEqualStrings("d", buf.screen.cellAt(3, 0).?.content); try t.expectEqualStrings("e", buf.screen.cellAt(0, 1).?.content); try t.expectEqualStrings("f", buf.screen.cellAt(1, 1).?.content); try t.expectEqual(Pos{ .x = 2, .y = 1 }, ctx.position()); } test "context printf and println" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); var buf: ir.Screen = try .init(t.allocator, 12, 3); defer buf.deinit(); var ctx = Context.init(&buf.screen, arena.allocator()); _ = try ctx.printf("{d}+{d} = {d}", .{ 1, 2, 3 }); try t.expectEqualStrings("1", buf.screen.cellAt(0, 0).?.content); try t.expectEqualStrings("+", buf.screen.cellAt(1, 0).?.content); try t.expectEqualStrings("=", buf.screen.cellAt(4, 0).?.content); try t.expectEqualStrings("3", buf.screen.cellAt(6, 0).?.content); try t.expectEqual(Pos{ .x = 7, .y = 0 }, ctx.position()); _ = try ctx.println("hello", .{}); try t.expectEqualStrings("h", buf.screen.cellAt(7, 0).?.content); try t.expectEqual(Pos{ .x = 0, .y = 2 }, ctx.position()); } test "context style and link flow into cells" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); var buf: ir.Screen = try .init(t.allocator, 6, 1); defer buf.deinit(); var ctx = Context.init(&buf.screen, arena.allocator()); ctx.setURL("https://example.com", "id=1"); ctx.setUnderline(true); try ctx.drawString("link", 0, 0); try t.expectEqual(.single, buf.screen.cellAt(0, 0).?.style.underline); try t.expectEqualStrings("https://example.com", buf.screen.cellAt(0, 0).?.link.url); try t.expectEqualStrings("id=1", buf.screen.cellAt(3, 0).?.link.params); } test "fuzz context draw" { try t.fuzz({}, fuzzContextDraw, .{ .corpus = &.{ "", "Hello, World!", "a世b", "\n\n\n", "a\u{301}b", "a\u{301}世\u{200d}界", "\x1b[31m\x1b[0m", "a世\nb", }, }); } fn fuzzContextDraw(_: void, smith: *t.Smith) anyerror!void { var input: [512]u8 = undefined; const len = smith.slice(&input); const s = input[0..len]; var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const alloc = arena.allocator(); var buf: ir.Screen = try .init(t.allocator, 16, 8); defer buf.deinit(); var ctx = Context.init(&buf.screen, alloc); const x: Size = @intCast(smith.index(20)); const y: Size = @intCast(smith.index(10)); try ctx.drawString(s, x, y); try ctx.drawStringWrapped(s, x, y); ctx.moveTo(x, y); _ = try ctx.write(s); ctx.moveTo(x, y); _ = try ctx.writeString(s); _ = try ctx.print("{s}", .{s}); _ = try ctx.println("{s}", .{s}); }