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 var img1 = try vaxis.zigimg.Image.fromFilePath(alloc, "examples/zig.png");
37 defer img1.deinit();
38
39 const imgs = [_]vaxis.Image{
40 try vx.transmitImage(alloc, tty.anyWriter(), &img1, .rgba),
41 // var img1 = try vaxis.zigimg.Image.fromFilePath(alloc, "examples/zig.png");
42 // try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/zig.png" }),
43 try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/vaxis.png" }),
44 };
45 defer vx.freeImage(tty.anyWriter(), imgs[0].id);
46 defer vx.freeImage(tty.anyWriter(), imgs[1].id);
47
48 var n: usize = 0;
49
50 var clip_y: usize = 0;
51
52 while (true) {
53 const event = loop.nextEvent();
54 switch (event) {
55 .key_press => |key| {
56 if (key.matches('c', .{ .ctrl = true })) {
57 return;
58 } else if (key.matches('l', .{ .ctrl = true })) {
59 vx.queueRefresh();
60 } else if (key.matches('j', .{}))
61 clip_y += 1
62 else if (key.matches('k', .{}))
63 clip_y -|= 1;
64 },
65 .winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
66 }
67
68 n = (n + 1) % imgs.len;
69 const win = vx.window();
70 win.clear();
71
72 const img = imgs[n];
73 const dims = try img.cellSize(win);
74 const center = vaxis.widgets.alignment.center(win, dims.cols, dims.rows);
75 try img.draw(center, .{ .scale = .contain, .clip_region = .{
76 .y = clip_y,
77 } });
78
79 try vx.render(tty.anyWriter());
80 }
81}