79113
Ma
mini-coding-agent / files
mini-coding-agent / src / tui / term.zig
3.1 KB
1const std = @import("std"); 2const platform = @import("../platform.zig"); 3 4const EXIT_SEQUENCE = "\x1b[<u\x1b[?2004l"; 5const ENTER_SEQUENCE = "\x1b[?2004h\x1b[>1u\x1b[?u"; 6 7const fallback_cell = [2]usize{ 10, 20 }; 8 9var saved: std.posix.termios = undefined; 10var raw_mode = std.atomic.Value(bool).init(false); 11var entered = std.atomic.Value(bool).init(false); 12 13fn writeRaw(bytes: []const u8) void { 14 _ = std.posix.system.write(std.posix.STDOUT_FILENO, bytes.ptr, bytes.len); 15} 16 17pub fn restore() void { 18 if (raw_mode.swap(false, .seq_cst)) std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, saved) catch {}; 19 if (entered.swap(false, .seq_cst)) writeRaw(EXIT_SEQUENCE); 20} 21 22pub const Terminal = struct { 23 started: bool = false, 24 winsize: [2]usize = .{ 80, 24 }, 25 pixels: [2]usize = .{ 0, 0 }, 26 27 pub fn width(self: *Terminal) usize { 28 return self.winsize[0]; 29 } 30 31 pub fn height(self: *Terminal) usize { 32 return self.winsize[1]; 33 } 34 35 pub fn cell(self: *Terminal) [2]usize { 36 const w = if (self.winsize[0] > 0 and self.pixels[0] > 0) self.pixels[0] / self.winsize[0] else fallback_cell[0]; 37 const h = if (self.winsize[1] > 0 and self.pixels[1] > 0) self.pixels[1] / self.winsize[1] else fallback_cell[1]; 38 return .{ @max(w, 1), @max(h, 1) }; 39 } 40 41 pub fn refreshSize(self: *Terminal) void { 42 var wsz: std.posix.winsize = .{ .row = 0, .col = 0, .xpixel = 0, .ypixel = 0 }; 43 const r = platform.io.operate(.{ .device_io_control = .{ 44 .file = std.Io.File.stdout(), 45 .code = std.posix.T.IOCGWINSZ, 46 .arg = &wsz, 47 } }) catch return; 48 if (r.device_io_control >= 0) { 49 if (wsz.col > 0) self.winsize[0] = wsz.col; 50 if (wsz.row > 0) self.winsize[1] = wsz.row; 51 if (wsz.xpixel > 0) self.pixels[0] = wsz.xpixel; 52 if (wsz.ypixel > 0) self.pixels[1] = wsz.ypixel; 53 } 54 } 55 56 pub fn start(self: *Terminal) void { 57 if (self.started) return; 58 self.started = true; 59 self.refreshSize(); 60 if (std.Io.File.stdin().isTty(platform.io) catch false) { 61 const original = std.posix.tcgetattr(std.posix.STDIN_FILENO) catch return; 62 var raw = original; 63 raw.lflag.ICANON = false; 64 raw.lflag.ECHO = false; 65 raw.lflag.ISIG = false; 66 raw.lflag.IEXTEN = false; 67 raw.iflag.ICRNL = false; 68 raw.iflag.IXON = false; 69 raw.oflag.OPOST = false; 70 raw.cc[@backingInt(std.posix.V.MIN)] = 1; 71 raw.cc[@backingInt(std.posix.V.TIME)] = 0; 72 saved = original; 73 raw_mode.store(true, .seq_cst); 74 std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, raw) catch { 75 raw_mode.store(false, .seq_cst); 76 return; 77 }; 78 } 79 entered.store(true, .seq_cst); 80 platform.writeOut(ENTER_SEQUENCE); 81 } 82 83 pub fn stop(self: *Terminal) void { 84 if (!self.started) return; 85 self.started = false; 86 restore(); 87 } 88 89 pub fn write(self: *Terminal, text: []const u8) void { 90 _ = self; 91 platform.writeOut(text); 92 } 93};