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