From 8c8caf4769cdeed2010346c278b23e6b905f0ae3 Mon Sep 17 00:00:00 2001 From: Tim Culverhouse Date: Fri, 19 Jan 2024 10:58:14 -0600 Subject: [PATCH] tty: enable writing to tty and add smcup in example Signed-off-by: Tim Culverhouse --- examples/main.zig | 2 ++ src/Tty.zig | 8 ++++++++ src/vaxis.zig | 29 +++++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/examples/main.zig b/examples/main.zig index ce65859..c985fdd 100644 --- a/examples/main.zig +++ b/examples/main.zig @@ -19,6 +19,8 @@ pub fn main() !void { try vx.start(); defer vx.stop(); + try vx.enterAltScreen(); + outer: while (true) { const event = vx.nextEvent(); log.debug("event: {}\r\n", .{event}); diff --git a/src/Tty.zig b/src/Tty.zig index 8c13f50..e6d48c6 100644 --- a/src/Tty.zig +++ b/src/Tty.zig @@ -167,6 +167,13 @@ pub fn run( } } +/// write to the tty +// +// TODO: buffer the writes +pub fn write(self: *Tty, bytes: []const u8) !usize { + return os.write(self.fd, bytes); +} + /// makeRaw enters the raw state for the terminal. pub fn makeRaw(fd: os.fd_t) !os.termios { const state = try os.tcgetattr(fd); @@ -218,6 +225,7 @@ fn ior(inout: u32, group: usize, num: usize, len: usize) usize { return (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num)); } +/// The size of the terminal screen pub const Winsize = struct { rows: usize, cols: usize, diff --git a/src/vaxis.zig b/src/vaxis.zig index e78fb22..3278ab8 100644 --- a/src/vaxis.zig +++ b/src/vaxis.zig @@ -1,6 +1,7 @@ const std = @import("std"); -const queue = @import("queue.zig"); +const Queue = @import("queue.zig").Queue; +const ctlseqs = @import("ctlseqs.zig"); const Tty = @import("Tty.zig"); const Key = @import("Key.zig"); const Screen = @import("Screen.zig"); @@ -27,18 +28,21 @@ pub fn Vaxis(comptime T: type) type { /// the event queue for Vaxis // // TODO: is 512 ok? - queue: queue.Queue(T, 512), + queue: Queue(T, 512), tty: ?Tty, screen: Screen, + alt_screen: bool, + /// Initialize Vaxis with runtime options pub fn init(_: Options) !Self { return Self{ .queue = .{}, .tty = null, .screen = Screen.init(), + .alt_screen = false, }; } @@ -49,6 +53,9 @@ pub fn Vaxis(comptime T: type) type { pub fn deinit(self: *Self, alloc: ?std.mem.Allocator) void { if (self.tty) |_| { var tty = &self.tty.?; + if (self.alt_screen) { + _ = tty.write(ctlseqs.rmcup) catch {}; + } tty.deinit(); } if (alloc) |a| self.screen.deinit(a); @@ -98,6 +105,24 @@ pub fn Vaxis(comptime T: type) type { .screen = &self.screen, }; } + + pub fn enterAltScreen(self: *Self) !void { + if (self.tty) |_| { + var tty = &self.tty.?; + _ = try tty.write(ctlseqs.smcup); + self.alt_screen = true; + } + } + + pub fn exitaltScreen(self: *Self) !void { + if (self.tty) |_| { + if (!self.alt_screen) return; + + var tty = &self.tty.?; + _ = try tty.write(ctlseqs.rmcup); + self.alt_screen = false; + } + } }; }