summaryrefslogtreecommitdiff
path: root/src/ansi.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 03:25:13 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commita3509e4df5efc94b0deee3b06dd72f85b0d96647 (patch)
tree86be50532fe55f9232c7ba59c3e5007895f7f85e /src/ansi.zig
parent98f84f99e79cccc2344aff2efe10823540d0c7b7 (diff)
downloadpardes-a3509e4df5efc94b0deee3b06dd72f85b0d96647.tar.gz
pardes-a3509e4df5efc94b0deee3b06dd72f85b0d96647.zip
Term: the draw group as plain data (docs/next-terminal.md, Phase 1): the terminal paints its view into a plain cell buffer and the core lays it over the body's rows; Term.paint gives each of its view's rows (Term.PaintedRow: the prompt cut a shell's marks make of it, its kitty placeholders, how many cells it has) and each cell (Term.Painted: its style in the theme's colours, through the filter when the pane has it on, the bytes it spells, its width) for a theme handed in as Term.Ink; src/ansi.zig, new, is the core's half of what was terminal.zig's recolorAnsi, moved: the body walk, the edit copy's anchors (EditAnchors, its rows from Term.editRows) and the grapheme-to-cell alignment, now reading the buffer instead of the emulator's pages, and drawImages' body walk (Term.images takes the rows it maps and appends placements to the frame's list, blanking placeholder cells in its cells, as TerminalImages.draw did through Pardes); the filter stays the terminal's (it wraps ghostty's generate256Color), its record plain (Term.Filter, Term.FilterPalette in src/plain/term.zig, [3]u8 for ghostty's RGB), so a +Pager's spans are drawn through Term.filter and Term.spanColor, and palColor is Ink.palColor; config.tty_filter_min_contrast goes to the filter it bounds; Term.Grid gains the grid's cols; the filter tests reach the plain record's fields through asGhostRgb, asserting what they did; perf --terminal-mib (tail-style line off, ReleaseFast, instructions:u, 3 runs each, ±30k): 8 MiB 4,347.9M -> 3,949.8M (4.51M -> 4.09M a batch), 32 MiB 14,729.1M -> 13,294.4M (3.82M -> 3.45M a batch), the copy costs nothing that shows and the frame got cheaper; core-test 985/985, kitty-test 45/45, pane-test 151/152 (1 skipped), behaviour-test 268/272 (the four addon ABI 3.0 tests the base fails), replicas checked/wrong 0
Diffstat (limited to 'src/ansi.zig')
-rw-r--r--src/ansi.zig305
1 files changed, 305 insertions, 0 deletions
diff --git a/src/ansi.zig b/src/ansi.zig
new file mode 100644
index 00000000..3a3f9d85
--- /dev/null
+++ b/src/ansi.zig
@@ -0,0 +1,305 @@
+//! A program's colours on a pane's body: a terminal's cells over the rows
+//! the body shows (its paint, handed over as plain cells: Term.paint), and
+//! its kitty images over them (Term.images). The terminal gives its view's
+//! cells in the theme's colours; which of them stand under which of the
+//! body's rows, the edit copy's among them, is worked out here.
+const std = @import("std");
+const pardes = @import("pardes.zig");
+const panes = @import("panes.zig");
+const modal = @import("modal.zig");
+const tracy = @import("tracy.zig");
+const Term = @import("Term.zig");
+const Pardes = pardes.Pardes;
+const Pane = panes.Pane;
+const Surface = pardes.Surface;
+const BodyWalk = @import("body_layer.zig").BodyWalk;
+const EditBuffer = panes.Text.EditBuffer;
+
+/// The theme's colours as a terminal's paint takes them.
+pub fn inkOf(theme: *const pardes.Theme) Term.Ink {
+ return .{
+ .fg = theme.fg,
+ .bg = theme.bg,
+ .tag_fg = theme.tag_fg,
+ .tag_bg = theme.tag_bg,
+ .palette = theme.palette,
+ .base = theme.palette orelse .{
+ theme.bg orelse theme.tag_bg,
+ theme.kw,
+ theme.str,
+ theme.num,
+ theme.box,
+ theme.sel_bg,
+ theme.comment,
+ theme.fg orelse theme.tag_fg,
+ theme.lineno,
+ theme.kw,
+ theme.str,
+ theme.num,
+ theme.scroll_thumb,
+ theme.sel_fg,
+ theme.tag_fg,
+ theme.fg orelse theme.tag_fg,
+ },
+ };
+}
+
+/// Its program's colours over the body's rows, through the theme's filter
+/// when the pane has it on.
+pub fn recolor(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void {
+ const state = pane.terminal orelse return;
+ const body_y = p.bodyTop(pane, r);
+ const g = Term.grid(state);
+ const cols = g.cols;
+ const arena = p.scratch.allocator();
+ const cells = arena.alloc(Term.Painted, g.len * @as(usize, cols)) catch return;
+ const rows = arena.alloc(Term.PaintedRow, g.len) catch return;
+ {
+ const tz_paint = tracy.zone(@src(), "termPaint");
+ defer tz_paint.end();
+ const ink = inkOf(p.theme());
+ Term.paint(state, &ink, &p.tty_filter_palette, pane.tty_filter, cols, cells, rows);
+ }
+ const filtered = pane.tty_filter;
+ const vp_rows: i32 = @intCast(g.len);
+ // Which buffer lines the user has not actually changed, so a row swallowed
+ // by a growing buffer keeps the colour it still stands over.
+ var anchors: ?EditAnchors = null;
+ var walk: BodyWalk = .init(pane);
+ var lines = std.mem.splitScalar(u8, body, '\n');
+ var vr: u16 = 0;
+ while (walk.next()) |row| : (vr += 1) {
+ if (vr >= body_h) break;
+ // Before any early exit below, or the lines fall out of step with rows.
+ const text = lines.next() orelse "";
+ const anchor: Anchor = switch (row) {
+ .edit => |e| blk: {
+ if (anchors == null) anchors = .init(p, pane, pane.ovl.?);
+ var an = anchors.?.shellRow(e.idx) orelse continue;
+ an.row -= walk.goff;
+ break :blk an;
+ },
+ .grid => |v| .{ .row = v },
+ };
+ const vi = anchor.row;
+ if (vi < 0 or vi >= vp_rows) continue;
+ const prow = rows[@intCast(vi)];
+ const grid_row = cells[@as(usize, @intCast(vi)) * cols ..][0..prow.len];
+ const cut: u16 = if (pane.body.mode == .tty) 0 else cut: {
+ const prompt = prow.prompt orelse break :cut 0;
+ break :cut switch (prompt) {
+ .keep => 0,
+ // Blanked end to end: the row shows nothing of the grid, so
+ // projecting the prompt's own colours onto it would be a lie.
+ .blank => continue,
+ .cut => |n| std.math.cast(u16, n) orelse continue,
+ };
+ };
+ if (cut > 0 and text.len == 0) continue;
+ var at: usize = 0;
+ var sc: u16 = 0;
+ var gc: u16 = cut;
+ var sb: usize = 0;
+ const mine_from = @min(anchor.prefix, text.len);
+ const mine_to = text.len - @min(anchor.suffix, text.len);
+ var crossed = false;
+ while (at < text.len and sc < tw) {
+ const stop = modal.nextGrapheme(text, at);
+ if (stop <= at) break;
+ const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1;
+ if (at >= mine_from and at < mine_to) {
+ sc += span;
+ at = stop;
+ continue;
+ }
+ if (at >= mine_to and !crossed) {
+ crossed = true;
+ const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len);
+ while (sb < upto) {
+ if (gc >= grid_row.len) break;
+ sb += grid_row[gc].bytes;
+ gc = std.math.add(u16, gc, 1) catch break;
+ }
+ }
+ const want = stop - at;
+ // Consume every cell that contributed to this grapheme. A cluster
+ // ghostty split across several cells is still ONE printed glyph.
+ var covered: usize = 0;
+ var style: ?pardes.CellStyle = null;
+ while (covered < want) {
+ if (gc >= grid_row.len) break;
+ const c = &grid_row[gc];
+ if (style == null and c.wide != .spacer_tail and c.wide != .spacer_head)
+ style = c.style;
+ covered += c.bytes;
+ gc = std.math.add(u16, gc, 1) catch break;
+ // A spacer contributes no bytes; without this the loop would
+ // spin on a row that ends in one.
+ if (covered == 0 and gc >= pane.cols) break;
+ }
+ while (gc < grid_row.len and grid_row[gc].wide == .spacer_tail)
+ gc = std.math.add(u16, gc, 1) catch break;
+ if (style) |st| for (0..span) |k| {
+ const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr);
+ if (cell.default and !filtered) continue;
+ cell.default = false;
+ cell.style = st;
+ };
+ sb += covered;
+ sc += span;
+ at = stop;
+ }
+ var tail: ?pardes.CellStyle = null;
+ if (anchor.whole() or anchor.suffix > 0) {
+ while (sc < tw) {
+ if (gc >= grid_row.len) break;
+ const c = &grid_row[gc];
+ gc = std.math.add(u16, gc, 1) catch break;
+ if (c.wide == .spacer_tail) continue;
+ const cell = s.at(tx + sc, body_y + vr);
+ sc += 1;
+ tail = c.style;
+ if (cell.default and !filtered) continue;
+ cell.default = false;
+ cell.style = c.style;
+ }
+ if (tail) |style| while (sc < tw) : (sc += 1) {
+ const cell = s.at(tx + sc, body_y + vr);
+ if (cell.default and !filtered) continue;
+ cell.default = false;
+ cell.style = style;
+ };
+ }
+ }
+}
+
+/// Its kitty images over the body's rows, as placements (after the rows
+/// and their colours: placeholder cells are blanked by it).
+pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void {
+ const state = pane.terminal orelse return;
+ Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h);
+ // A body taller than this draws its images on the rows that fit.
+ var rows_of: [1024]?u16 = undefined;
+ const vp_rows: usize = @min(Term.grid(state).len, rows_of.len);
+ @memset(rows_of[0..vp_rows], null);
+ var walk: BodyWalk = .init(pane);
+ var vr: u16 = 0;
+ while (walk.next()) |row| : (vr += 1) {
+ if (vr >= body_h) break;
+ const vi = switch (row) {
+ .grid => |v| v,
+ .edit => continue,
+ };
+ if (vi < 0 or vi >= vp_rows) continue;
+ rows_of[@intCast(vi)] = vr;
+ }
+ Term.images(state, p.gpa, .{
+ .pane = @intCast(id),
+ .serial = pane.serial,
+ .tx = tx,
+ .body_y = body_y,
+ .cols = @min(tw, pane.cols),
+ .rows_of = rows_of[0..vp_rows],
+ .tty_mode = pane.body.mode == .tty,
+ .now_ms = p.clock.stepped_ns / std.time.ns_per_ms,
+ .cell_w = @max(1, p.view().cell_pixels.w),
+ .cell_h = @max(1, p.view().cell_pixels.h),
+ }, &p.surface.placements, s.cells, s.cols);
+}
+
+// Match surviving edit-buffer rows to their original terminal styles.
+const EditAnchors = struct {
+ /// the buffer's own text, walked in order: a line the VIEWPORT skipped still
+ /// consumes the row it came from, so the lines below it stay aligned
+ text: []const u8 = &.{},
+ at: usize = 0,
+ shell: []const []const u8 = &.{},
+ /// the covered span, absolute grid rows, as `[first, end)`
+ first: usize = 0,
+ end: usize = 0,
+ lines: usize = 0,
+ /// the line `at` names, and the first row still unclaimed
+ idx: usize = 0,
+ cursor: usize = 0,
+ budget: usize = 0,
+ active: bool = false,
+
+ fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors {
+ if (o.rows <= 0 or o.row < 0) return .{};
+ const first: usize = @intCast(o.row);
+ const total = Term.grid(pane.terminal).total;
+ if (first >= total) return .{};
+ const covered: usize = @intCast(o.rows);
+ const count = @min(covered, total - first);
+ const shell = Term.editRows(pane.terminal.?, p.scratch.allocator(), first, count) catch return .{};
+ const lines = std.mem.count(u8, o.text, "\n") + 1;
+ return .{
+ .text = o.text,
+ .shell = shell,
+ .first = first,
+ .end = first + count,
+ .lines = lines,
+ .cursor = first,
+ .budget = covered + 4 * lines,
+ .active = true,
+ };
+ }
+ fn shellRow(a: *EditAnchors, idx: usize) ?Anchor {
+ if (!a.active or idx >= a.lines) return null;
+ var found: ?Anchor = null;
+ while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null);
+ return found;
+ }
+
+ fn nextLine(a: *EditAnchors) ?[]const u8 {
+ if (a.at > a.text.len) return null;
+ const rest = a.text[a.at..];
+ if (std.mem.indexOfScalar(u8, rest, '\n')) |n| {
+ a.at += n + 1;
+ return rest[0..n];
+ }
+ // The last line has no terminator; one past the end ends the walk.
+ a.at = a.text.len + 1;
+ return rest;
+ }
+
+ /// Where this line still stands over the grid, if anywhere.
+ fn claim(a: *EditAnchors, line: []const u8) ?Anchor {
+ const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end;
+ var k = a.cursor;
+ while (k < end) : (k += 1) {
+ if (a.budget == 0) return null;
+ a.budget -= 1;
+ if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue;
+ a.cursor = k + 1;
+ return .{ .row = @intCast(k) };
+ }
+ if (a.cursor >= a.end) return null;
+ const shell = a.shell[a.cursor - a.first];
+ var p: usize = 0;
+ while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1;
+ var s: usize = 0;
+ const room = @min(line.len, shell.len) - p;
+ while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1;
+ if (p + s == 0) return null;
+ if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null;
+ const row = a.cursor;
+ if (s > 0 or p >= shell.len) a.cursor += 1;
+ return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len };
+ }
+};
+
+const Anchor = struct {
+ /// the row, absolute while it comes from `EditAnchors`, viewport once
+ /// `recolorAnsi` has subtracted the walk's offset
+ row: i32,
+ prefix: usize = std.math.maxInt(usize),
+ suffix: usize = 0,
+ /// the row's own dumped length — what the suffix is measured from on the
+ /// GRID side, where the edit may have changed the byte count
+ shell_len: usize = 0,
+
+ fn whole(an: Anchor) bool {
+ return an.prefix == std.math.maxInt(usize);
+ }
+};