a modern tui library written in zig
1const std = @import("std");
2const vaxis = @import("vaxis");
3
4const log = std.log.scoped(.main);
5
6const Event = union(enum) {
7 key_press: vaxis.Key,
8 winsize: vaxis.Winsize,
9};
10
11pub fn main() !void {
12 var gpa = std.heap.GeneralPurposeAllocator(.{}){};
13 defer {
14 const deinit_status = gpa.deinit();
15 if (deinit_status == .leak) {
16 log.err("memory leak", .{});
17 }
18 }
19 const alloc = gpa.allocator();
20
21 var tty = try vaxis.Tty.init();
22 defer tty.deinit();
23
24 var vx = try vaxis.init(alloc, .{});
25 defer vx.deinit(alloc, tty.anyWriter());
26
27 var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
28 try loop.init();
29
30 try loop.start();
31 defer loop.stop();
32
33 try vx.enterAltScreen(tty.anyWriter());
34 try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
35
36 const imgs = [_]vaxis.Image{
37 try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/zig.png" }),
38 try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/vaxis.png" }),
39 };
40 defer vx.freeImage(tty.anyWriter(), imgs[0].id);
41 defer vx.freeImage(tty.anyWriter(), imgs[1].id);
42
43 var n: usize = 0;
44
45 var clip_y: usize = 0;
46
47 while (true) {
48 const event = loop.nextEvent();
49 switch (event) {
50 .key_press => |key| {
51 if (key.matches('c', .{ .ctrl = true })) {
52 return;
53 } else if (key.matches('l', .{ .ctrl = true })) {
54 vx.queueRefresh();
55 } else if (key.matches('j', .{}))
56 clip_y += 1
57 else if (key.matches('k', .{}))
58 clip_y -|= 1;
59 },
60 .winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
61 }
62
63 n = (n + 1) % imgs.len;
64 const win = vx.window();
65 win.clear();
66
67 const img = imgs[n];
68 const dims = try img.cellSize(win);
69 const center = vaxis.widgets.alignment.center(win, dims.cols, dims.rows);
70 try img.draw(center, .{ .scale = .contain, .clip_region = .{
71 .y = clip_y,
72 } });
73
74 try vx.render(tty.anyWriter());
75 }
76}