From 9df08455302ba4a195b479f0eed716abe0522169 Mon Sep 17 00:00:00 2001 From: utox39 Date: Thu, 31 Jul 2025 01:43:40 +0200 Subject: [PATCH] feat: add a utility function to retrieve the terminal size --- src/utils.zig | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/utils.zig diff --git a/src/utils.zig b/src/utils.zig new file mode 100644 index 0000000..0520d6c --- /dev/null +++ b/src/utils.zig @@ -0,0 +1,51 @@ +const std = @import("std"); +const builtin = @import("builtin"); + +pub const TermSize = struct { + width: u16, + height: u16, +}; + +pub fn getTerminalSize() !TermSize { + // https://github.com/softprops/zig-termsize (https://github.com/softprops/zig-termsize/blob/main/src/main.zig) + + const stdout = std.io.getStdIn(); + + switch (builtin.os.tag) { + .windows => { + var buf: std.os.windows.CONSOLE_SCREEN_BUFFER_INFO = undefined; + switch (std.os.windows.kernel32.GetConsoleScreenBufferInfo(stdout.handle, &buf)) { + std.os.windows.TRUE => return TermSize{ + .width = @intCast(buf.srWindow.Right - buf.srWindow.Left + 1), + .height = @intCast(buf.srWindow.Bottom - buf.srWindow.Top + 1), + }, + else => return error.GetConsoleScreenBufferInfoFailed, + } + }, + .linux, .macos => { + var buf: std.posix.winsize = undefined; + switch (std.posix.errno( + std.posix.system.ioctl( + stdout.handle, + std.posix.T.IOCGWINSZ, + @intFromPtr(&buf), + ), + )) { + std.posix.E.SUCCESS => return TermSize{ + .width = buf.col, + .height = buf.row, + }, + else => return error.IoctlFailed, + } + }, + else => return error.UnsupportedOperatingSystem, + } +} + +test "getTerminalSize" { + const terminal_size = try getTerminalSize(); + + std.debug.print("Height: {}, Width {}\n", .{ terminal_size.height, terminal_size.width }); + + try std.testing.expect((terminal_size.height > 0) and (terminal_size.width > 0)); +}