-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathLoop.zig
More file actions
424 lines (394 loc) · 17.2 KB
/
Loop.zig
File metadata and controls
424 lines (394 loc) · 17.2 KB
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
const std = @import("std");
const builtin = @import("builtin");
const GraphemeCache = @import("GraphemeCache.zig");
const Parser = @import("Parser.zig");
const Queue = @import("queue.zig").Queue;
const vaxis = @import("main.zig");
const ascii = @import("ascii.zig");
const Tty = vaxis.Tty;
const Vaxis = @import("Vaxis.zig");
const log = std.log.scoped(.vaxis);
pub fn Loop(comptime T: type) type {
return struct {
const Self = @This();
const Event = T;
tty: *Tty,
vaxis: *Vaxis,
queue: Queue(T, 512) = .{},
thread: ?std.Thread = null,
should_quit: bool = false,
/// Initialize the event loop. This is an intrusive init so that we have
/// a stable pointer to register signal callbacks with posix TTYs
pub fn init(self: *Self) !void {
switch (builtin.os.tag) {
.windows => {},
else => {
if (!builtin.is_test) {
const handler: Tty.SignalHandler = .{
.context = self,
.callback = Self.winsizeCallback,
};
try Tty.notifyWinsize(handler);
}
},
}
}
/// spawns the input thread to read input from the tty
pub fn start(self: *Self) !void {
if (self.thread) |_| return;
self.thread = try std.Thread.spawn(.{}, Self.ttyRun, .{
self,
self.vaxis.opts.system_clipboard_allocator,
});
}
/// stops reading from the tty.
pub fn stop(self: *Self) void {
// If we don't have a thread, we have nothing to stop
if (self.thread == null) return;
self.should_quit = true;
// trigger a read
self.vaxis.deviceStatusReport(self.tty.writer()) catch {};
if (self.thread) |thread| {
thread.join();
self.thread = null;
self.should_quit = false;
}
}
/// returns the next available event, blocking until one is available
pub fn nextEvent(self: *Self) T {
return self.queue.pop();
}
/// blocks until an event is available. Useful when your application is
/// operating on a poll + drain architecture (see tryEvent)
pub fn pollEvent(self: *Self) void {
self.queue.poll();
}
/// returns an event if one is available, otherwise null. Non-blocking.
pub fn tryEvent(self: *Self) ?T {
return self.queue.tryPop();
}
/// posts an event into the event queue. Will block if there is not
/// capacity for the event
pub fn postEvent(self: *Self, event: T) void {
self.queue.push(event);
}
pub fn tryPostEvent(self: *Self, event: T) bool {
return self.queue.tryPush(event);
}
pub fn winsizeCallback(ptr: *anyopaque) void {
const self: *Self = @ptrCast(@alignCast(ptr));
// We will be receiving winsize updates in-band
if (self.vaxis.state.in_band_resize) return;
const winsize = Tty.getWinsize(self.tty.fd) catch return;
if (@hasField(Event, "winsize")) {
self.postEvent(.{ .winsize = winsize });
}
}
/// read input from the tty. This is run in a separate thread
fn ttyRun(
self: *Self,
paste_allocator: ?std.mem.Allocator,
) !void {
// Return early if we're in test mode to avoid infinite loops
if (builtin.is_test) return;
// initialize a grapheme cache
var cache: GraphemeCache = .{};
switch (builtin.os.tag) {
.windows => {
var parser: Parser = .{};
while (!self.should_quit) {
const event = try self.tty.nextEvent(&parser, paste_allocator);
try handleEventGeneric(self, self.vaxis, &cache, Event, event, null);
}
},
else => {
// get our initial winsize
const winsize = try Tty.getWinsize(self.tty.fd);
if (@hasField(Event, "winsize")) {
self.postEvent(.{ .winsize = winsize });
}
var parser: Parser = .{};
// initialize the read buffer
var buf: [1024]u8 = undefined;
var read_start: usize = 0;
// read loop
read_loop: while (!self.should_quit) {
const n = try self.tty.read(buf[read_start..]);
const total = read_start + n;
var seq_start: usize = 0;
while (seq_start < total) {
if (@hasField(Event, "key_press")) {
const input = buf[seq_start..total];
const ascii_len = ascii.fastPathLen(input);
if (ascii_len > 0) {
var i: usize = 0;
while (i < ascii_len) : (i += 1) {
const key: vaxis.Key = .{
.codepoint = input[i],
.text = input[i .. i + 1],
};
const event: Event = .{ .key_press = key };
try handleEventGeneric(self, self.vaxis, &cache, Event, event, paste_allocator);
}
read_start = 0;
seq_start += ascii_len;
continue;
}
}
const result = try parser.parse(buf[seq_start..total], paste_allocator);
if (result.n == 0) {
// copy the read to the beginning. We don't use memcpy because
// this could be overlapping, and it's also rare
const initial_start = seq_start;
while (seq_start < total) : (seq_start += 1) {
buf[seq_start - initial_start] = buf[seq_start];
}
read_start = total - initial_start;
continue :read_loop;
}
read_start = 0;
seq_start += result.n;
const event = result.event orelse continue;
try handleEventGeneric(self, self.vaxis, &cache, Event, event, paste_allocator);
}
}
},
}
}
};
}
// Use return on the self.postEvent's so it can either return error union or void
pub fn handleEventGeneric(self: anytype, vx: *Vaxis, cache: *GraphemeCache, Event: type, event: anytype, paste_allocator: ?std.mem.Allocator) !void {
switch (builtin.os.tag) {
.windows => {
switch (event) {
.winsize => |ws| {
if (@hasField(Event, "winsize")) {
return self.postEvent(.{ .winsize = ws });
}
},
.key_press => |key| {
// Check for a cursor position response for our explicit width query. This will
// always be an F3 key with shift = true, and we must be looking for queries
if (key.codepoint == vaxis.Key.f3 and
key.mods.shift and
!vx.queries_done.load(.unordered))
{
log.info("explicit width capability detected", .{});
vx.caps.explicit_width = true;
vx.caps.unicode = .unicode;
vx.screen.width_method = .unicode;
return;
}
// Check for a cursor position response for our scaled text query. This will
// always be an F3 key with alt = true, and we must be looking for queries
if (key.codepoint == vaxis.Key.f3 and
key.mods.alt and
!vx.queries_done.load(.unordered))
{
log.info("scaled text capability detected", .{});
vx.caps.scaled_text = true;
return;
}
if (@hasField(Event, "key_press")) {
// HACK: yuck. there has to be a better way
var mut_key = key;
if (key.text) |text| {
mut_key.text = cache.put(text);
}
return self.postEvent(.{ .key_press = mut_key });
}
},
.key_release => |key| {
if (@hasField(Event, "key_release")) {
// HACK: yuck. there has to be a better way
var mut_key = key;
if (key.text) |text| {
mut_key.text = cache.put(text);
}
return self.postEvent(.{ .key_release = mut_key });
}
},
.cap_da1 => {
std.Thread.Futex.wake(&vx.query_futex, 10);
vx.queries_done.store(true, .unordered);
},
.mouse => |mouse| {
if (@hasField(Event, "mouse")) {
return self.postEvent(.{ .mouse = vx.translateMouse(mouse) });
}
},
.focus_in => {
if (@hasField(Event, "focus_in")) {
return self.postEvent(.focus_in);
}
},
.focus_out => {
if (@hasField(Event, "focus_out")) {
return self.postEvent(.focus_out);
}
}, // Unsupported currently
else => {},
}
},
else => {
switch (event) {
.key_press => |key| {
// Check for a cursor position response for our explicity width query. This will
// always be an F3 key with shift = true, and we must be looking for queries
if (key.codepoint == vaxis.Key.f3 and
key.mods.shift and
!vx.queries_done.load(.unordered))
{
log.info("explicit width capability detected", .{});
vx.caps.explicit_width = true;
vx.caps.unicode = .unicode;
vx.screen.width_method = .unicode;
return;
}
// Check for a cursor position response for our scaled text query. This will
// always be an F3 key with alt = true, and we must be looking for queries
if (key.codepoint == vaxis.Key.f3 and
key.mods.alt and
!vx.queries_done.load(.unordered))
{
log.info("scaled text capability detected", .{});
vx.caps.scaled_text = true;
return;
}
if (@hasField(Event, "key_press")) {
// HACK: yuck. there has to be a better way
var mut_key = key;
if (key.text) |text| {
mut_key.text = cache.put(text);
}
return self.postEvent(.{ .key_press = mut_key });
}
},
.key_release => |key| {
if (@hasField(Event, "key_release")) {
// HACK: yuck. there has to be a better way
var mut_key = key;
if (key.text) |text| {
mut_key.text = cache.put(text);
}
return self.postEvent(.{ .key_release = mut_key });
}
},
.mouse => |mouse| {
if (@hasField(Event, "mouse")) {
return self.postEvent(.{ .mouse = vx.translateMouse(mouse) });
}
},
.mouse_leave => {
if (@hasField(Event, "mouse_leave")) {
return self.postEvent(.mouse_leave);
}
},
.focus_in => {
if (@hasField(Event, "focus_in")) {
return self.postEvent(.focus_in);
}
},
.focus_out => {
if (@hasField(Event, "focus_out")) {
return self.postEvent(.focus_out);
}
},
.paste_start => {
if (@hasField(Event, "paste_start")) {
return self.postEvent(.paste_start);
}
},
.paste_end => {
if (@hasField(Event, "paste_end")) {
return self.postEvent(.paste_end);
}
},
.paste => |text| {
if (@hasField(Event, "paste")) {
return self.postEvent(.{ .paste = text });
} else {
if (paste_allocator) |_|
paste_allocator.?.free(text);
}
},
.color_report => |report| {
if (@hasField(Event, "color_report")) {
return self.postEvent(.{ .color_report = report });
}
},
.color_scheme => |scheme| {
if (@hasField(Event, "color_scheme")) {
return self.postEvent(.{ .color_scheme = scheme });
}
},
.cap_kitty_keyboard => {
log.info("kitty keyboard capability detected", .{});
vx.caps.kitty_keyboard = true;
},
.cap_kitty_graphics => {
if (!vx.caps.kitty_graphics) {
log.info("kitty graphics capability detected", .{});
vx.caps.kitty_graphics = true;
}
},
.cap_rgb => {
log.info("rgb capability detected", .{});
vx.caps.rgb = true;
},
.cap_unicode => {
log.info("unicode capability detected", .{});
vx.caps.unicode = .unicode;
vx.screen.width_method = .unicode;
},
.cap_sgr_pixels => {
log.info("pixel mouse capability detected", .{});
vx.caps.sgr_pixels = true;
},
.cap_color_scheme_updates => {
log.info("color_scheme_updates capability detected", .{});
vx.caps.color_scheme_updates = true;
},
.cap_multi_cursor => {
log.info("multi cursor capability detected", .{});
vx.caps.multi_cursor = true;
},
.cap_da1 => {
std.Thread.Futex.wake(&vx.query_futex, 10);
vx.queries_done.store(true, .unordered);
},
.winsize => |winsize| {
vx.state.in_band_resize = true;
switch (builtin.os.tag) {
.windows => {},
// Reset the signal handler if we are receiving in_band_resize
else => Tty.resetSignalHandler(),
}
if (@hasField(Event, "winsize")) {
return self.postEvent(.{ .winsize = winsize });
}
},
}
},
}
}
test Loop {
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
focus_in,
foo: u8,
};
var tty = try vaxis.Tty.init(&.{});
defer tty.deinit();
var vx = try vaxis.init(std.testing.allocator, .{});
defer vx.deinit(std.testing.allocator, tty.writer());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
// Optionally enter the alternate screen
try vx.enterAltScreen(tty.writer());
try vx.queryTerminal(tty.writer(), 1 * std.time.ns_per_ms);
}