1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
|
//! 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. And a
//! finished command pane's diff, coloured over those cells as a .diff
//! file's lines are (DiffOutput, recolorDiffOutput).
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 syntax = @import("syntax.zig");
const diff = @import("diff.zig");
const Colors = @import("colors.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 vp_rows: i32 = @intCast(g.len);
// The view's rows the body shows, an edit copy's among them: only they
// are painted (a pane shorter than its terminal, as one is until the
// terminal is resized to it, shows few of its rows).
var lo: i32 = vp_rows;
var hi: i32 = 0;
{
var shown: BodyWalk = .init(pane);
var n: u16 = 0;
while (shown.next()) |row| : (n += 1) {
if (n >= body_h) break;
// A copy's line stands over one of the rows the copy covers.
const from: i32, const to: i32 = switch (row) {
.grid => |v| .{ v, v + 1 },
.edit => .{ pane.ovl.?.row - shown.goff, pane.ovl.?.row + pane.ovl.?.rows - shown.goff },
};
lo = @min(lo, from);
hi = @max(hi, to);
}
}
lo = @max(lo, 0);
hi = @min(hi, vp_rows);
if (lo >= hi) return;
const arena = p.scratch.allocator();
const cells = arena.alloc(Term.Painted, @as(usize, @intCast(hi - lo)) * cols) catch return;
const rows = arena.alloc(Term.PaintedRow, @intCast(hi - lo)) 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, @intCast(lo), cols, cells, rows);
}
const filtered = pane.tty_filter;
// 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 < lo or vi >= hi) continue;
const prow = rows[@intCast(vi - lo)];
const grid_row = cells[@as(usize, @intCast(vi - lo)) * 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);
}
};
/// What finished command panes printed, kept while it cannot change: a
/// copy of the terminal's rows, and whether they are a diff. Taken once
/// when a finished pane is first drawn, so neither a frame nor a look dumps
/// the whole scrollback again; a still running command is shown as it
/// printed. Keyed by the pane and its width (a resize rewraps every row);
/// a rerun in the pane drops it (exec.runCommand).
pub const DiffOutput = struct {
const Entry = struct {
serial: u32,
cols: u16,
is_diff: bool,
/// The rows joined by '\n'; `rows` are slices of it.
text: []u8,
rows: [][]const u8,
used: u64,
};
slots: [4]?Entry = @splat(null),
clock: u64 = 0,
pub fn reset(o: *DiffOutput, gpa: std.mem.Allocator) void {
for (&o.slots) |*slot| {
if (slot.*) |e| {
gpa.free(e.text);
gpa.free(e.rows);
}
slot.* = null;
}
}
/// A pane's command runs again: what it printed before is gone.
pub fn drop(o: *DiffOutput, gpa: std.mem.Allocator, serial: u32) void {
for (&o.slots) |*slot| if (slot.*) |e| if (e.serial == serial) {
gpa.free(e.text);
gpa.free(e.rows);
slot.* = null;
};
}
/// A finished command pane's rows when they are a diff, else null.
pub fn lines(o: *DiffOutput, p: *Pardes, pane: *Pane) ?[]const []const u8 {
if (pane.command == null or !pane.command_done or pane.command_pty or pane.terminal == null) return null;
o.clock += 1;
for (&o.slots) |*slot| if (slot.*) |*e| if (e.serial == pane.serial and e.cols == pane.cols) {
e.used = o.clock;
return if (e.is_diff) e.rows else null;
};
const shown = pardes.edit.shellRows(p, pane) catch return null;
const is_diff = diff.looksLikeDiff(shown);
var total: usize = 0;
if (is_diff) for (shown) |row| {
total += row.len + 1;
};
const text = p.gpa.alloc(u8, total) catch return null;
const rows = p.gpa.alloc([]const u8, if (is_diff) shown.len else 0) catch {
p.gpa.free(text);
return null;
};
var at: usize = 0;
for (rows, 0..) |*row, i| {
@memcpy(text[at..][0..shown[i].len], shown[i]);
row.* = text[at..][0..shown[i].len];
at += shown[i].len;
text[at] = '\n';
at += 1;
}
// An empty slot, else the least recently used.
var oldest: usize = 0;
for (&o.slots, 0..) |*slot, i| {
const e = slot.* orelse {
oldest = i;
break;
};
if (e.used < o.slots[oldest].?.used) oldest = i;
}
if (o.slots[oldest]) |old| {
p.gpa.free(old.text);
p.gpa.free(old.rows);
}
o.slots[oldest] = .{ .serial = pane.serial, .cols = pane.cols, .is_diff = is_diff, .text = text, .rows = rows, .used = o.clock };
return if (is_diff) rows else null;
}
};
/// A command pane whose output is a diff (`git diff`, `diff -u`): its
/// rows coloured as a .diff file's are, over what the program printed.
/// The rows are the terminal's own, so a line it wrapped goes on in the
/// row below (syntax.highlightDiffRows).
pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void {
if (pane.command == null) return;
const tz = tracy.zone(@src(), "diffRecolor");
defer tz.end();
const rows = p.diff_output.lines(p, pane) orelse return;
// The copy's rows are one text, joined as a file's lines are.
const flat_start = @intFromPtr(rows[0].ptr);
const last = rows[rows.len - 1];
const flat = rows[0].ptr[0 .. @intFromPtr(last.ptr) + last.len - flat_start];
const raw = pane.body.mode == .tty;
const View = struct { row: usize, at: usize };
const arena = p.scratch.allocator();
const views = arena.alloc(?View, body_h) catch return;
var lo: usize = std.math.maxInt(usize);
var hi: usize = 0;
var shown = std.mem.splitScalar(u8, body, '\n');
for (views, 0..) |*view, vi| {
view.* = null;
const line = shown.next() orelse continue;
const vr: i32 = @intCast(vi);
const w = pane.wrapAt(vr);
const row_i: i32 = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + vr else w.line;
if (row_i < 0 or row_i >= @as(i64, @intCast(rows.len))) continue;
const row: usize = @intCast(row_i);
const from: usize = if (raw) 0 else @intCast(@max(0, w.at));
if (from > rows[row].len or !std.mem.startsWith(u8, rows[row][from..], line)) continue;
view.* = .{ .row = row, .at = from };
const start = @intFromPtr(rows[row].ptr) - flat_start;
lo = @min(lo, start);
hi = @max(hi, start + rows[row].len);
}
if (lo > hi) return;
const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return;
const tints: Colors.Grounds = .of(p.theme());
const ink = p.theme().fg orelse p.theme().tag_fg;
const body_y = p.bodyTop(pane, r);
shown = std.mem.splitScalar(u8, body, '\n');
for (views, 0..) |maybe, vr| {
const line = shown.next() orelse break;
const view = maybe orelse continue;
const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo;
const tint = if (base < styles.len) tints.forStyle(styles[base]) else null;
if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.row, null);
var c: usize = 0;
var screen_c: usize = 0;
while (c < line.len and screen_c < tw) {
const grapheme_end = modal.nextGrapheme(line, c);
if (grapheme_end <= c) break;
const cells = panes.File.graphemeDisplayWidth(line[c..grapheme_end]);
const style = styles[base + view.at + c];
const prefix = view.at + c == 0 and (line[0] == '+' or line[0] == '-');
// On an added or removed line, what the program coloured red or
// green is the tint's to say now: its code takes the page's ink.
const paint: ?panes.File.SynStyle = if (tint != null and prefix)
.{ .fg = tint.?.ink, .bold = true }
else if (panes.File.synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss|
ss
else if (tint != null)
.{ .fg = ink, .bold = false }
else
null;
if (paint) |ss| {
var fill: usize = 0;
while (fill < cells and screen_c + fill < tw) : (fill += 1) {
const cell = s.at(tx + @as(u16, @intCast(screen_c + fill)), body_y + @as(u16, @intCast(vr)));
if (cell.default) continue;
cell.style.fg = .{ .rgb = ss.fg };
cell.style.bold = ss.bold;
}
}
screen_c += cells;
c = grapheme_end;
}
}
}
|