a modern tui library written in zig
1const std = @import("std");
2const vaxis = @import("vaxis");
3const Cell = vaxis.Cell;
4
5// Our Event. This can contain internal events as well as Vaxis events.
6// Internal events can be posted into the same queue as vaxis events to allow
7// for a single event loop with exhaustive switching. Booya
8const Event = union(enum) {
9 key_press: vaxis.Key,
10 winsize: vaxis.Winsize,
11 focus_in,
12 nvim: vaxis.widgets.nvim.Event,
13};
14
15pub fn main() !void {
16 var gpa = std.heap.GeneralPurposeAllocator(.{}){};
17 defer {
18 const deinit_status = gpa.deinit();
19 //fail test; can't try in defer as defer is executed after we return
20 if (deinit_status == .leak) {
21 std.log.err("memory leak", .{});
22 }
23 }
24 const alloc = gpa.allocator();
25
26 var tty = try vaxis.Tty.init();
27 defer tty.deinit();
28
29 // Initialize Vaxis
30 var vx = try vaxis.init(alloc, .{});
31 defer vx.deinit(alloc, tty.anyWriter());
32
33 var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
34 try loop.init();
35
36 try loop.start();
37 defer loop.stop();
38
39 // Optionally enter the alternate screen
40 // try vx.enterAltScreen(tty.anyWriter());
41 try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
42
43 var nvim = try vaxis.widgets.nvim.Nvim(Event).init(alloc, &loop);
44 try nvim.spawn();
45 defer nvim.deinit();
46
47 // The main event loop. Vaxis provides a thread safe, blocking, buffered
48 // queue which can serve as the primary event queue for an application
49 while (true) {
50 // nextEvent blocks until an event is in the queue
51 const event = loop.nextEvent();
52 std.log.debug("event: {}", .{event});
53 // exhaustive switching ftw. Vaxis will send events if your Event
54 // enum has the fields for those events (ie "key_press", "winsize")
55 switch (event) {
56 .key_press => |key| {
57 try nvim.update(.{ .key_press = key });
58 },
59 .winsize => |ws| {
60 try vx.resize(alloc, tty.anyWriter(), ws);
61 },
62 .nvim => |nvim_event| {
63 switch (nvim_event) {
64 .redraw => {},
65 .quit => return,
66 }
67 },
68 else => {},
69 }
70
71 const win = vx.window();
72 win.clear();
73 const child = win.child(
74 .{
75 .height = .{ .limit = 40 },
76 .width = .{ .limit = 80 },
77 .border = .{ .where = .all },
78 },
79 );
80 try nvim.draw(child);
81 try vx.render(tty.anyWriter());
82 }
83}