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
|
const std = @import("std");
const libc = std.c;
const pardes = @import("core");
const selection_pipe = @import("core").selection_pipe;
const host_io = @import("host_io.zig");
const KindJob = host_io.KindJob;
const Lsp = host_io.Lsp;
const Inbox = @This();
pub const Msg = union(enum) {
output: struct { pane: pardes.Pane.Id, gen: u32, bytes: []u8 },
eof: struct { pane: pardes.Pane.Id, gen: u32, failure: ?anyerror = null },
lsp: struct { id: u32, rows: ?[]u8 },
lsp_status: []u8,
pipe: selection_pipe.Response,
/// A streaming search's rows (pardes.Stream), of whatever generation:
/// the core drops a stale one.
search: pardes.Stream.Batch,
/// How a handover went (Handover.zig): `words` is where it went, or
/// why it did not; gpa-owned.
handed: struct { seq: u32, ok: bool, words: []u8 },
/// A kind's job done on a worker (KindJob), never dropped.
kind_job: *KindJob,
files_changed,
fs_ready,
/// A shell a dead session left, its pty's master (Adopt); pid 0 is
/// the last of them told.
adopted: struct { pid: libc.pid_t, fd: c_int },
pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void {
switch (m) {
.output => |o| gpa.free(o.bytes),
.lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows),
.lsp_status => |t| lsp_allocator.free(t),
.pipe => |response_value| {
var response = response_value;
response.deinit(gpa);
},
.search => |b| b.deinit(gpa),
.handed => |h| gpa.free(h.words),
.kind_job => |j| j.drop(),
.adopted => |a| if (a.fd >= 0) {
_ = libc.close(a.fd);
},
.eof, .files_changed, .fs_ready => {},
}
}
};
pub const capacity = 512;
pub const output_capacity = capacity - pardes.MAX_PANES;
pub const Batch = struct {
items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
len: usize = 0,
pub fn slice(batch: *Batch) []Msg {
return batch.items[0..batch.len];
}
};
gpa: std.mem.Allocator,
lsp_allocator: std.mem.Allocator,
/// The query in flight; the UI thread's alone (spawnLsp, teardown).
lsp_task: ?Lsp.Task = null,
/// Wakes the host's loop after a push from another thread: an SDL
/// event, a macOS runtime callback. Null: nobody to wake (tests).
wake_fn: ?*const fn (?*anyopaque) void = null,
wake_ctx: ?*anyopaque = null,
/// The process's Io: its terminal readers wait for space on `space`.
io: std.Io,
mutex: std.Io.Mutex = .init,
space: std.Io.Condition = .init,
items: [capacity]Msg = undefined,
head: usize = 0,
len: usize = 0,
closed: bool = false,
files_changed: bool = false,
readers: [pardes.MAX_PANES]?u32 = @splat(null),
waiting: usize = 0,
lsp_id: ?u32 = null,
completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
completion_len: usize = 0,
pub fn lock(q: *Inbox) void {
q.mutex.lockUncancelable(q.io);
}
pub fn unlock(q: *Inbox) void {
q.mutex.unlock(q.io);
}
pub fn wake(q: *Inbox) void {
if (q.wake_fn) |f| f(q.wake_ctx);
}
pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.lock();
defer q.unlock();
std.debug.assert(q.readers[pane.index()] == null);
q.readers[pane.index()] = gen;
}
pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.lock();
defer q.unlock();
if (q.readers[pane.index()] != gen) return;
q.readers[pane.index()] = null;
var i: usize = 0;
while (i < q.len) {
const msg = q.items[(q.head + i) % q.items.len];
const matches = switch (msg) {
.output => |o| o.pane == pane and o.gen == gen,
.eof => |e| e.pane == pane and e.gen == gen,
else => false,
};
if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
}
q.space.broadcast(q.io);
}
pub fn pushOutput(q: *Inbox, pane: pardes.Pane.Id, gen: u32, bytes: []u8) bool {
q.lock();
while (!q.closed and q.readers[pane.index()] == gen and q.len >= output_capacity) {
q.waiting += 1;
q.space.waitUncancelable(q.io, &q.mutex);
q.waiting -= 1;
}
if (q.closed or q.readers[pane.index()] != gen) {
q.unlock();
q.gpa.free(bytes);
return false;
}
q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } };
q.len += 1;
q.unlock();
q.wake();
return true;
}
fn removeAt(q: *Inbox, offset: usize) Msg {
const removed = q.items[(q.head + offset) % q.items.len];
var i = offset;
while (i + 1 < q.len) : (i += 1)
q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len];
q.len -= 1;
return removed;
}
pub fn discardLsp(q: *Inbox) void {
for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) {
msg.deinit(q.gpa, q.lsp_allocator);
q.completion_len -= 1;
std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]);
return;
};
}
pub fn push(q: *Inbox, m: Msg) void {
if (m == .output) {
_ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes);
return;
}
q.lock();
if (q.closed) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
}
switch (m) {
.files_changed => q.files_changed = true,
.lsp, .pipe, .kind_job => {
if (m == .lsp) {
if (q.lsp_id != m.lsp.id) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
}
q.discardLsp();
}
std.debug.assert(q.completion_len < q.completions.len);
q.completions[q.completion_len] = m;
q.completion_len += 1;
},
else => {
if (m == .eof) {
if (q.readers[m.eof.pane.index()] != m.eof.gen) {
q.unlock();
return;
}
std.debug.assert(q.len < q.items.len);
} else if (q.len >= output_capacity) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
}
q.items[(q.head + q.len) % q.items.len] = m;
q.len += 1;
},
}
q.unlock();
q.wake();
}
pub fn take(q: *Inbox) Batch {
var batch: Batch = .{};
q.takeInto(&batch);
return batch;
}
/// `take` into a batch the caller keeps: an idle wakeup copies nothing
/// (the batch is some 20 KB, and was built and returned by value each
/// time).
pub fn takeInto(q: *Inbox, batch: *Batch) void {
batch.len = 0;
q.lock();
defer q.unlock();
if (q.len == 0 and !q.files_changed and q.completion_len == 0) return;
while (q.len > 0) {
batch.items[batch.len] = q.items[q.head];
batch.len += 1;
q.head = (q.head + 1) % q.items.len;
q.len -= 1;
}
q.head = 0;
if (q.files_changed) {
batch.items[batch.len] = .files_changed;
batch.len += 1;
q.files_changed = false;
}
@memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]);
batch.len += q.completion_len;
q.completion_len = 0;
q.space.broadcast(q.io);
}
pub fn discardCompletions(q: *Inbox) void {
q.lock();
defer q.unlock();
q.lsp_id = null;
for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator);
q.completion_len = 0;
}
pub fn close(q: *Inbox) void {
q.lock();
q.closed = true;
q.files_changed = false;
q.readers = @splat(null);
q.space.broadcast(q.io);
q.unlock();
q.discardCompletions();
q.lock();
defer q.unlock();
while (q.len > 0) {
const m = q.items[q.head];
m.deinit(q.gpa, q.lsp_allocator);
q.head = (q.head + 1) % q.items.len;
q.len -= 1;
}
q.head = 0;
}
pub fn deinit(q: *Inbox) void {
// The query in flight ends first: what it still delivers is dropped.
if (q.lsp_task) |*t| t.future.cancel(q.io);
q.lsp_task = null;
q.close();
std.debug.assert(q.waiting == 0);
}
/// A pane's reader: its pty's output pushed as it comes, then its end
/// of file; canceled (closePty), it pushes nothing more.
pub fn startReader(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) !std.Io.Future(void) {
q.acceptReader(pane, gen);
errdefer q.cancelReader(pane, gen);
return q.io.concurrent(readPty, .{ q, pty, pane, gen });
}
fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void {
var buf: [0x10000]u8 = undefined;
var failure: ?anyerror = null;
while (true) {
const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) {
// A pty whose child has gone answers EIO: its end of file.
error.EndOfStream, error.InputOutput => break,
error.Canceled => return,
else => {
failure = err;
break;
},
};
if (n == 0) continue;
const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
failure = err;
break;
};
if (!q.pushOutput(pane, gen, bytes)) return;
}
q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
}
/// Starts `e`, its answer let in and every older one's turned away.
pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
q.lock();
q.lsp_id = e.id;
q.discardLsp();
q.unlock();
// The old query's waits are cancelation points: its join is short, and
// what it still delivers carries an id the queue now rejects.
Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
}
/// A language server's answer or status line taken off the queue, to the
/// core (whichever frontend took it).
pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
switch (m) {
.lsp => |l| {
core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
if (l.rows) |rows| q.lsp_allocator.free(rows);
},
.lsp_status => |text| {
var mbuf: [256]u8 = undefined;
core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
q.lsp_allocator.free(text);
},
else => unreachable,
}
}
fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
q.push(.{ .lsp = .{ .id = id, .rows = rows } });
}
/// The language client's status line (lsp.setStatusSink).
pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
const copy = q.lsp_allocator.dupe(u8, text) catch return;
q.push(.{ .lsp_status = copy });
}
/// A `|` job's answer (selection_pipe.start's sink).
pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .kind_job = j });
}
pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .pipe = response });
}
/// A handover's end (Handover.Job.post).
pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
const copy = q.gpa.dupe(u8, words) catch return;
q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } });
}
/// A streaming search's batch (pardes.Stream.start's sink). Never
/// dropped for want of room, as output is not: the worker waits for
/// room, a wait its cancel ends (false: it stops).
pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.lock();
while (!q.closed and q.len >= output_capacity) {
q.waiting += 1;
q.space.wait(q.io, &q.mutex) catch {
q.waiting -= 1;
q.unlock();
batch.deinit(q.gpa);
return false;
};
q.waiting -= 1;
}
if (q.closed) {
q.unlock();
batch.deinit(q.gpa);
return false;
}
q.items[(q.head + q.len) % q.items.len] = .{ .search = batch };
q.len += 1;
q.unlock();
q.wake();
return true;
}
/// A watched child exited (setExitWake): wake the loop, which takes it.
pub fn wakeForExit(ctx: ?*anyopaque) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.wake();
}
|