~gpanders/wk

wk/src/tty.zig -rw-r--r-- 1.7 KiB
4f358b1aGregory Anders Import std.io in main.zig a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const std = @import("std");
const fs = std.fs;
const stdout = std.io.getStdOut();

pub const Color = enum(u8) {
    Black = 0,
    Red = 1,
    Green = 2,
    Yellow = 3,
    Blue = 4,
    Magenta = 5,
    Cyan = 6,
    White = 7,
    BrBlack = 8,
    BrRed = 9,
    BrGreen = 10,
    BrYellow = 11,
    BrBlue = 12,
    BrMagenta = 13,
    BrCyan = 14,
    BrWhite = 15,
};

pub const ColorWriter = struct {
    color: ?Color = null,
    bold: bool = false,
    italic: bool = false,
    file: fs.File,

    const Self = @This();

    pub fn new(file: fs.File) Self {
        return .{ .file = file };
    }

    pub fn setColor(self: Self, color: ?Color) Self {
        return .{ .color = color, .bold = self.bold, .italic = self.italic, .file = self.file };
    }

    pub fn print(self: Self, comptime format: []const u8, args: var) void {
        if (self.color) |_| {
            self.file.outStream().print("\x1b[38;5;{}m", .{@enumToInt(self.color.?)}) catch return;
        }

        if (self.bold) {
            self.file.outStream().print("\x1b[1m", .{}) catch return;
        }

        if (self.italic) {
            self.file.outStream().print("\x1b[3m", .{}) catch return;
        }

        self.file.outStream().print(format, args) catch return;

        self.file.outStream().print("\x1b[0m", .{}) catch return;
    }

    pub fn setBold(self: Self) Self {
        return .{ .color = self.color, .bold = true, .italic = self.italic, .file = self.file };
    }

    pub fn setItalic(self: Self) Self {
        return .{ .color = self.color, .bold = self.bold, .italic = true, .file = self.file };
    }

    pub fn reset(self: Self) Self {
        return .{ .color = null, .bold = false, .file = self.file };
    }
};