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
|
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 => {},
}
}
};
/// The ring's room: output up to `output_capacity` (a reader waits for
/// more), an Adopt's shells beyond it (one note's: never lost to a flood),
/// and each pane's end of file beyond those (lost to neither).
pub const output_capacity = 512 - pardes.MAX_PANES;
const adopt_capacity = output_capacity + pardes.MAX_PANES + 1;
pub const capacity = adopt_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,
/// The server start a file's opening asked for (openLsp); the UI
/// thread's alone.
lsp_opener: Lsp.Opener = .{},
/// The `|` pipes' and the addons' jobs' and draws' workers in flight, each
/// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's
/// alone: joined as their answers land (`land`), canceled at the end.
pipe_tasks: selection_pipe.Tasks = .{},
job_tasks: selection_pipe.Tasks = .{},
/// 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),
/// Each pane's reads read out of its pty and not yet applied (`applied`):
/// a command's exit is told only once none is (Ptys.unapplied), since
/// the poll that asks whether its output is in (CommandWatch.due) cannot
/// see a read the reader holds or the queue does.
unapplied: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)),
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;
}
/// One of `pane`'s reads applied, or dropped unapplied.
pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void {
const n = &q.unapplied[pane.index()];
if (n.load(.acquire) == 0) return;
_ = n.fetchSub(1, .acq_rel);
pardes.turn.outputApplied();
}
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) {
if (msg == .output) q.applied(pane);
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 >= @as(usize, if (m == .adopted) adopt_capacity else 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 workers in flight end first: what they still deliver is dropped.
if (q.lsp_task) |*t| t.future.cancel(q.io);
q.lsp_task = null;
if (q.lsp_opener.future) |*f| f.cancel(q.io);
q.lsp_opener.future = null;
q.pipe_tasks.cancelAll(q.io);
q.job_tasks.cancelAll(q.io);
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;
// Counted at once: out of the pty, the poll no longer sees it,
// nor a write after it (Turn.awaitOutput).
_ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel);
_ = pardes.turn.reads.fetchAdd(1, .acq_rel);
const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
q.applied(pane);
failure = err;
break;
};
if (!q.pushOutput(pane, gen, bytes)) return q.applied(pane);
}
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);
}
/// The language server of the file `pane` opened started, on a worker of
/// its own (Lsp.open).
pub fn openLsp(q: *Inbox, core: *const pardes.Pardes, pane: pardes.Pane.Id) void {
Lsp.open(q.io, q.lsp_allocator, core, &q.lsp_opener, pane);
}
/// A worker's answer taken off the queue, to the core (whichever frontend
/// took it), its worker joined: a language server's answer or status line,
/// a pipe's, a search's rows, an addon's job or draw, a handover's end.
pub fn land(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;
// A server's progress, of no pane: the workspace tag's.
core.setStatus(.at(pardes.MAX_PANES), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
q.lsp_allocator.free(text);
},
.pipe => |response_value| {
var response = response_value;
core.update(.{ .pipe_resp = .{
.id = response.id,
.success = response.success,
.outputs = response.outputs,
.failure = response.failure,
} });
response.deinit(q.gpa);
q.pipe_tasks.finish(q.io, response_value.id);
},
.search => |b| {
core.update(.{ .search = b });
b.deinit(q.gpa);
},
.kind_job => |j| {
q.job_tasks.finish(q.io, j.id);
j.land(core);
},
.handed => |h| {
core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
q.gpa.free(h.words);
},
.output, .eof, .files_changed, .fs_ready, .adopted => 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 });
}
/// An addon's job or draw done (KindJob.go's sink).
pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .kind_job = j });
}
/// A `|` pipe's answer (selection_pipe.start's sink).
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();
}
|