-
-
Notifications
You must be signed in to change notification settings - Fork 221
Color -> ANSI for chat in terminal #3224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Wunka
wants to merge
23
commits into
PixelGuys:master
Choose a base branch
from
Wunka:ANSI
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+258
−116
Open
Changes from 14 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
28779b7
Color -> ANSI
Wunka d6cfc88
remove todo
Wunka b90bc65
support more
Wunka d0157ac
kinda support everything
Wunka 62510f5
use unicode
Wunka f4b816e
fix other todo
Wunka 23f5b46
.
Wunka 6a393db
only add when there is more to come
Wunka b23edf4
fix incomplete ansi code
Wunka f08c4a6
use parse
Wunka edd54e4
move loggin
Wunka a8d01f4
remove unused function
Wunka b3be44d
mhh I didn't know you yould "expand" enums
Wunka 6a6cd37
sepearat chat and server messages
Wunka 7d4bcf8
Update src/log.zig
Wunka 8c4d56a
add std_options back
Wunka 12f3b7a
move std_options
Wunka d44a1da
move std_options back to main
Wunka 3606839
Update src/log.zig
Wunka f0f9932
better level parsing
Wunka 10eb301
switch allocator
Wunka 936cad7
change logic a bit
Wunka 74e8d96
fix typo
Wunka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,234 @@ | ||
| const std = @import("std"); | ||
| const main = @import("main"); | ||
| const files = main.files; | ||
| const fmt = main.fmt; | ||
| const graphics = main.graphics; | ||
| const gui = main.gui; | ||
| const List = main.List; | ||
| const settings = main.settings; | ||
|
|
||
| pub const Level = enum { | ||
| /// Error: something has gone wrong. This might be recoverable or might | ||
| /// be followed by the program exiting. | ||
| err, | ||
| /// Warning: it is uncertain if something has gone wrong or not, but the | ||
| /// circumstances would be worth investigating. | ||
| warn, | ||
| /// Info: general messages about the state of the program. | ||
| info, | ||
| /// Debug: messages only useful for debugging. | ||
| debug, | ||
| /// server messages | ||
| server, | ||
| /// chat messages | ||
| chat, | ||
|
|
||
| fn isColorCoded(self: Level) bool { | ||
| return self == .chat or self == .server; | ||
| } | ||
| }; | ||
|
|
||
| var logFile: ?std.Io.File = undefined; | ||
| var logFileTs: ?std.Io.File = undefined; | ||
| var supportsANSIColors: bool = undefined; | ||
| var openingErrorWindow: bool = false; | ||
|
|
||
| // overwrite the log function: | ||
| pub const std_options: std.Options = .{ // MARK: std_options | ||
| .log_level = .debug, | ||
| .logFn = struct { | ||
| pub fn logFn( | ||
| comptime level: std.log.Level, | ||
| comptime _: @EnumLiteral(), | ||
| comptime format: []const u8, | ||
| args: anytype, | ||
| ) void { | ||
| var runtimeArgs: [args.len]fmt.FormatArg = undefined; | ||
| inline for (0..args.len) |i| { | ||
| runtimeArgs[i] = .fromAnytype(@TypeOf(args[i]), &args[i]); | ||
| } | ||
| runtimeLogFn(level, format, &runtimeArgs); | ||
| } | ||
| }.logFn, | ||
| }; | ||
|
|
||
| noinline fn runtimeLogFn(level: Level, format: []const u8, args: []const fmt.FormatArg) void { | ||
| var buf: [65536]u8 = undefined; | ||
| var writer: std.Io.Writer = .fixed(&buf); | ||
| fmt.format(&writer, format, args) catch { | ||
| std.log.err("Truncated long log message.", .{}); | ||
| }; | ||
|
|
||
| const color: []const u8 = switch (level) { | ||
| .err => "\x1b[31m", | ||
| .info => "", | ||
| .warn => "\x1b[33m", | ||
| .debug => "\x1b[37;44m", | ||
| .server => "\x1b[34mserver\x1b[0m: ", | ||
| .chat => "\x1b[36mchat\x1b[0m: ", | ||
| }; | ||
| const colorReset = "\x1b[0m\n"; | ||
| const filePrefix = switch (level) { | ||
| .err => "error", | ||
| .warn => "warning", | ||
| .info => "info", | ||
| .debug => "debug", | ||
| .server => "server", | ||
| .chat => "chat", | ||
| }; | ||
| const fileSuffix = "\n"; | ||
|
|
||
| logToFile("[{s}]: {s}{s}", .{filePrefix, writer.buffered(), fileSuffix}); | ||
| if (supportsANSIColors) { | ||
| logToStdErr(level, "{s}{s}{s}", .{color, writer.buffered(), colorReset}); | ||
| } else { | ||
| logToStdErr(level, "[{s}]: {s}{s}", .{filePrefix, writer.buffered(), fileSuffix}); | ||
| } | ||
|
|
||
| if (level == .err and !openingErrorWindow and !settings.launchConfig.headlessServer) { | ||
| openingErrorWindow = true; | ||
| gui.openWindow("error_prompt"); | ||
| openingErrorWindow = false; | ||
| } | ||
| } | ||
|
|
||
| pub fn init() void { | ||
| logFile = null; | ||
| files.cwd().makePath("logs") catch |err| { | ||
| std.log.err("Couldn't create logs folder: {s}", .{@errorName(err)}); | ||
| return; | ||
| }; | ||
| logFile = std.Io.Dir.cwd().createFile(main.io, "logs/latest.log", .{}) catch |err| { | ||
| std.log.err("Couldn't create logs/latest.log: {s}", .{@errorName(err)}); | ||
| return; | ||
| }; | ||
|
|
||
| const _timestamp = std.Io.Clock.Timestamp.now(main.io, .real).raw; | ||
|
|
||
| const _path_str = std.fmt.allocPrint(main.stackAllocator.allocator, "logs/ts_{}.log", .{_timestamp.nanoseconds}) catch unreachable; | ||
| defer main.stackAllocator.free(_path_str); | ||
|
|
||
| logFileTs = std.Io.Dir.cwd().createFile(main.io, _path_str, .{}) catch |err| { | ||
| std.log.err("Couldn't create {s}: {s}", .{_path_str, @errorName(err)}); | ||
| return; | ||
| }; | ||
|
|
||
| supportsANSIColors = std.Io.File.stdout().supportsAnsiEscapeCodes(main.io) catch unreachable; | ||
| } | ||
|
|
||
| pub fn deinit() void { | ||
| if (logFile) |_logFile| { | ||
| _logFile.close(main.io); | ||
| logFile = null; | ||
| } | ||
|
|
||
| if (logFileTs) |_logFileTs| { | ||
| _logFileTs.close(main.io); | ||
| logFileTs = null; | ||
| } | ||
| } | ||
|
|
||
| fn logToFile(comptime format: []const u8, args: anytype) void { | ||
| var buf: [65536]u8 = undefined; | ||
| var fba = std.heap.FixedBufferAllocator.init(&buf); | ||
| const allocator = fba.allocator(); | ||
|
|
||
| const string = std.fmt.allocPrint(allocator, format, args) catch format; | ||
| (logFile orelse return).writeStreamingAll(main.io, string) catch {}; | ||
| (logFileTs orelse return).writeStreamingAll(main.io, string) catch {}; | ||
| } | ||
|
|
||
| fn logToStdErr(level: Level, comptime format: []const u8, args: anytype) void { | ||
| var buf: [65536]u8 = undefined; | ||
| var fba = std.heap.FixedBufferAllocator.init(&buf); | ||
| const allocator = fba.allocator(); | ||
|
|
||
| const _string = std.fmt.allocPrint(allocator, format, args) catch format; | ||
| const string = if (level.isColorCoded() and supportsANSIColors) convertColorToANSI(_string) else _string; | ||
| defer if (level.isColorCoded() and supportsANSIColors) main.stackAllocator.free(string); | ||
|
|
||
| const writer = std.debug.lockStderr(&.{}); | ||
| defer std.debug.unlockStderr(); | ||
| nosuspend writer.file_writer.interface.writeAll(string) catch {}; | ||
| } | ||
|
|
||
| pub fn convertColorToANSI(text: []const u8) []const u8 { | ||
|
Wunka marked this conversation as resolved.
Outdated
|
||
| var list: List(u8) = .empty; | ||
|
|
||
| var parser = graphics.TextBuffer.Parser{ | ||
| .unicodeIterator = std.unicode.Utf8Iterator{.bytes = text, .i = 0}, | ||
| .currentFontEffect = .{}, | ||
| .parsedText = .init(main.stackAllocator), | ||
| .fontEffects = .init(main.stackAllocator), | ||
| .characterIndex = .init(main.stackAllocator), | ||
| .showControlCharacters = false, | ||
| }; | ||
| defer parser.fontEffects.deinit(); | ||
| defer parser.parsedText.deinit(); | ||
| defer parser.characterIndex.deinit(); | ||
| parser.parse(); | ||
|
|
||
| parser.currentFontEffect = .{}; | ||
|
Wunka marked this conversation as resolved.
Outdated
|
||
| for (0..parser.parsedText.items.len) |i| { | ||
| if (parser.fontEffects.items[i].color != parser.currentFontEffect.color) { | ||
| list.appendSlice(main.stackAllocator, "\x1b[38;2"); | ||
| var shift: u5 = 16; | ||
| while (true) : (shift -= 8) { | ||
| list.print(main.stackAllocator, ";{d}", .{@as(u8, @truncate(parser.fontEffects.items[i].color >> shift))}); | ||
| if (shift == 0) break; | ||
| } | ||
| list.append(main.stackAllocator, 'm'); | ||
| } | ||
| if (parser.fontEffects.items[i].bold != parser.currentFontEffect.bold) { | ||
| list.appendSlice(main.stackAllocator, "\x1b["); | ||
|
Wunka marked this conversation as resolved.
Outdated
|
||
| if (!parser.currentFontEffect.bold) { | ||
| list.append(main.stackAllocator, '1'); | ||
| } else { | ||
| list.appendSlice(main.stackAllocator, "22"); | ||
| } | ||
| list.append(main.stackAllocator, 'm'); | ||
| } | ||
| if (parser.fontEffects.items[i].italic != parser.currentFontEffect.italic) { | ||
| list.appendSlice(main.stackAllocator, "\x1b["); | ||
| if (parser.currentFontEffect.italic) { | ||
| list.append(main.stackAllocator, '2'); | ||
| } | ||
| list.appendSlice(main.stackAllocator, "3m"); | ||
| } | ||
| if (parser.fontEffects.items[i].strikethrough != parser.currentFontEffect.strikethrough) { | ||
| list.appendSlice(main.stackAllocator, "\x1b["); | ||
| if (parser.currentFontEffect.strikethrough) { | ||
| list.append(main.stackAllocator, '2'); | ||
| } | ||
| list.appendSlice(main.stackAllocator, "9m"); | ||
| } | ||
| if (parser.fontEffects.items[i].underline != parser.currentFontEffect.underline) { | ||
| list.appendSlice(main.stackAllocator, "\x1b["); | ||
| if (parser.currentFontEffect.underline) { | ||
| list.append(main.stackAllocator, '2'); | ||
| } | ||
| list.appendSlice(main.stackAllocator, "4m"); | ||
| } | ||
| parser.currentFontEffect = parser.fontEffects.items[i]; | ||
| var testBuff: [3]u8 = undefined; | ||
| const len = std.unicode.utf8Encode(@truncate(parser.parsedText.items[i]), &testBuff) catch continue; | ||
|
Wunka marked this conversation as resolved.
Outdated
|
||
| list.appendSlice(main.stackAllocator, testBuff[0..len]); | ||
| } | ||
| return list.toOwnedSlice(main.stackAllocator); | ||
| } | ||
|
|
||
| pub fn server(comptime format: []const u8, args: anytype) void { | ||
| var runtimeArgs: [args.len]fmt.FormatArg = undefined; | ||
| inline for (0..args.len) |i| { | ||
| runtimeArgs[i] = .fromAnytype(@TypeOf(args[i]), &args[i]); | ||
| } | ||
| runtimeLogFn(.server, format, &runtimeArgs); | ||
| } | ||
|
|
||
| pub fn chat(comptime format: []const u8, args: anytype) void { | ||
| var runtimeArgs: [args.len]fmt.FormatArg = undefined; | ||
| inline for (0..args.len) |i| { | ||
| runtimeArgs[i] = .fromAnytype(@TypeOf(args[i]), &args[i]); | ||
| } | ||
| runtimeLogFn(.chat, format, &runtimeArgs); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.