Support multiple info lines in UI

Signed-off-by: AnErrupTion <anerruption@disroot.org>
This commit is contained in:
AnErrupTion
2024-07-31 13:58:49 +02:00
parent 961018e753
commit a393525212
6 changed files with 94 additions and 65 deletions

View File

@@ -1,6 +1,11 @@
const std = @import("std");
const utils = @import("../utils.zig");
const TerminalBuffer = @import("../TerminalBuffer.zig");
const generic = @import("generic.zig");
const utils = @import("../utils.zig");
const Allocator = std.mem.Allocator;
const MessageLabel = generic.CyclableLabel(Message);
const InfoLine = @This();
@@ -10,24 +15,23 @@ const Message = struct {
bg: u16,
fg: u16,
};
const MessageList = std.ArrayList(Message);
messages: MessageList,
label: MessageLabel,
pub fn init(allocator: std.mem.Allocator) InfoLine {
pub fn init(allocator: Allocator, buffer: *TerminalBuffer, max_length: usize) !InfoLine {
return .{
.messages = MessageList.init(allocator),
.label = try MessageLabel.init(allocator, buffer, max_length, drawItem),
};
}
pub fn deinit(self: InfoLine) void {
self.messages.deinit();
self.label.deinit();
}
pub fn addMessage(self: *InfoLine, text: []const u8, bg: u16, fg: u16) !void {
if (text.len == 0) return;
try self.messages.append(.{
try self.label.addItem(.{
.width = try utils.strWidth(text),
.text = text,
.bg = bg,
@@ -35,18 +39,7 @@ pub fn addMessage(self: *InfoLine, text: []const u8, bg: u16, fg: u16) !void {
});
}
pub fn draw(self: InfoLine, buffer: TerminalBuffer) !void {
if (self.messages.items.len == 0) return;
const entry = self.messages.getLast();
if (entry.width == 0 or buffer.box_width <= entry.width) return;
const label_y = buffer.box_y + buffer.margin_box_v;
const x = buffer.box_x + ((buffer.box_width - entry.width) / 2);
TerminalBuffer.drawColorLabel(entry.text, x, label_y, entry.fg, entry.bg);
}
pub fn clearRendered(allocator: std.mem.Allocator, buffer: TerminalBuffer) !void {
pub fn clearRendered(allocator: Allocator, buffer: TerminalBuffer) !void {
// Draw over the area
const y = buffer.box_y + buffer.margin_box_v;
const spaces = try allocator.alloc(u8, buffer.box_width);
@@ -56,3 +49,13 @@ pub fn clearRendered(allocator: std.mem.Allocator, buffer: TerminalBuffer) !void
buffer.drawLabel(spaces, buffer.box_x, y);
}
fn drawItem(label: *MessageLabel, message: Message, _: usize, _: usize) bool {
if (message.width == 0 or label.buffer.box_width <= message.width) return false;
const x = label.buffer.box_x + ((label.buffer.box_width - message.width) / 2);
label.first_char_x = x;
TerminalBuffer.drawColorLabel(message.text, x, label.y, message.fg, message.bg);
return true;
}