a modern tui library written in zig
1const std = @import("std");
2const assert = std.debug.assert;
3
4const Cell = @import("Cell.zig");
5const Shape = @import("Mouse.zig").Shape;
6const Image = @import("Image.zig");
7const Winsize = @import("main.zig").Winsize;
8const Unicode = @import("Unicode.zig");
9const Method = @import("gwidth.zig").Method;
10
11const log = std.log.scoped(.screen);
12
13const Screen = @This();
14
15width: usize = 0,
16height: usize = 0,
17
18width_pix: usize = 0,
19height_pix: usize = 0,
20
21buf: []Cell = undefined,
22
23cursor_row: usize = 0,
24cursor_col: usize = 0,
25cursor_vis: bool = false,
26
27unicode: *const Unicode = undefined,
28
29width_method: Method = .wcwidth,
30
31mouse_shape: Shape = .default,
32cursor_shape: Cell.CursorShape = .default,
33
34pub fn init(alloc: std.mem.Allocator, winsize: Winsize, unicode: *const Unicode) !Screen {
35 const w = winsize.cols;
36 const h = winsize.rows;
37 const self = Screen{
38 .buf = try alloc.alloc(Cell, w * h),
39 .width = w,
40 .height = h,
41 .width_pix = winsize.x_pixel,
42 .height_pix = winsize.y_pixel,
43 .unicode = unicode,
44 };
45 const base_cell: Cell = .{};
46 @memset(self.buf, base_cell);
47 return self;
48}
49pub fn deinit(self: *Screen, alloc: std.mem.Allocator) void {
50 alloc.free(self.buf);
51}
52
53/// writes a cell to a location. 0 indexed
54pub fn writeCell(self: *Screen, col: usize, row: usize, cell: Cell) void {
55 if (self.width <= col) {
56 // column out of bounds
57 return;
58 }
59 if (self.height <= row) {
60 // height out of bounds
61 return;
62 }
63 const i = (row * self.width) + col;
64 assert(i < self.buf.len);
65 self.buf[i] = cell;
66}
67
68pub fn readCell(self: *Screen, col: usize, row: usize) ?Cell {
69 if (self.width <= col) {
70 // column out of bounds
71 return null;
72 }
73 if (self.height <= row) {
74 // height out of bounds
75 return null;
76 }
77 const i = (row * self.width) + col;
78 assert(i < self.buf.len);
79 return self.buf[i];
80}