feat(element/progress): Progress bar implementation as an Element
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 2m42s
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 2m42s
This commit is contained in:
@@ -10,6 +10,7 @@ pub fn build(b: *std.Build) void {
|
||||
alignment,
|
||||
button,
|
||||
input,
|
||||
progress,
|
||||
scrollable,
|
||||
// layouts:
|
||||
vertical,
|
||||
@@ -60,6 +61,7 @@ pub fn build(b: *std.Build) void {
|
||||
.alignment => "examples/elements/alignment.zig",
|
||||
.button => "examples/elements/button.zig",
|
||||
.input => "examples/elements/input.zig",
|
||||
.progress => "examples/elements/progress.zig",
|
||||
.scrollable => "examples/elements/scrollable.zig",
|
||||
// layouts:
|
||||
.vertical => "examples/layouts/vertical.zig",
|
||||
|
||||
137
examples/elements/progress.zig
Normal file
137
examples/elements/progress.zig
Normal file
@@ -0,0 +1,137 @@
|
||||
const QuitText = struct {
|
||||
const text = "Press ctrl+c to quit.";
|
||||
|
||||
pub fn element(this: *@This()) App.Element {
|
||||
return .{ .ptr = this, .vtable = &.{ .content = content } };
|
||||
}
|
||||
|
||||
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
|
||||
_ = ctx;
|
||||
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
|
||||
|
||||
const row = 2;
|
||||
const col = size.x / 2 -| (text.len / 2);
|
||||
const anchor = (row * size.x) + col;
|
||||
|
||||
for (text, 0..) |cp, idx| {
|
||||
cells[anchor + idx].style.fg = .white;
|
||||
cells[anchor + idx].style.bg = .black;
|
||||
cells[anchor + idx].cp = cp;
|
||||
|
||||
// NOTE do not write over the contents of this `Container`'s `Size`
|
||||
if (anchor + idx == cells.len - 1) break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub fn main() !void {
|
||||
errdefer |err| log.err("Application Error: {any}", .{err});
|
||||
|
||||
var gpa: std.heap.DebugAllocator(.{}) = .init;
|
||||
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
|
||||
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
var app: App = .init;
|
||||
var renderer = zterm.Renderer.Buffered.init(allocator);
|
||||
defer renderer.deinit();
|
||||
|
||||
var progress_percent: u8 = 0;
|
||||
var progress: App.Progress(.progress) = .init(&app.queue, .{
|
||||
.percent = .{ .enabled = true },
|
||||
.fg = .green,
|
||||
.bg = .grey,
|
||||
});
|
||||
var quit_text: QuitText = .{};
|
||||
|
||||
var container = try App.Container.init(allocator, .{
|
||||
.layout = .{ .padding = .all(5) },
|
||||
}, quit_text.element());
|
||||
defer container.deinit();
|
||||
|
||||
try container.append(try App.Container.init(allocator, .{}, progress.element()));
|
||||
|
||||
try app.start();
|
||||
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
|
||||
|
||||
var framerate: u64 = 60;
|
||||
var tick_ms: u64 = @divFloor(time.ms_per_s, framerate);
|
||||
var next_frame_ms: u64 = 0;
|
||||
|
||||
var increase_progress: u64 = 10;
|
||||
|
||||
// Continuous drawing
|
||||
// draw loop
|
||||
draw: while (true) {
|
||||
const now_ms: u64 = @intCast(time.milliTimestamp());
|
||||
if (now_ms >= next_frame_ms) {
|
||||
next_frame_ms = now_ms + tick_ms;
|
||||
} else {
|
||||
time.sleep((next_frame_ms - now_ms) * time.ns_per_ms);
|
||||
next_frame_ms += tick_ms;
|
||||
}
|
||||
|
||||
// NOTE time based progress increasion
|
||||
increase_progress -= 1;
|
||||
if (increase_progress == 0) {
|
||||
increase_progress = 10;
|
||||
progress_percent += 1;
|
||||
if (progress_percent > 100) progress_percent = 0;
|
||||
app.postEvent(.{ .progress = progress_percent });
|
||||
}
|
||||
|
||||
const len = blk: {
|
||||
app.queue.lock();
|
||||
defer app.queue.unlock();
|
||||
break :blk app.queue.len();
|
||||
};
|
||||
|
||||
// handle events
|
||||
for (0..len) |_| {
|
||||
const event = app.queue.drain() orelse break;
|
||||
log.debug("handling event: {s}", .{@tagName(event)});
|
||||
// pre event handling
|
||||
switch (event) {
|
||||
.key => |key| {
|
||||
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
|
||||
},
|
||||
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
|
||||
.focus => |b| {
|
||||
// NOTE reduce framerate in case the window is not focused and restore again when focused
|
||||
framerate = if (b) 60 else 15;
|
||||
tick_ms = @divFloor(time.ms_per_s, framerate);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
|
||||
container.handle(event) catch |err| app.postEvent(.{
|
||||
.err = .{
|
||||
.err = err,
|
||||
.msg = "Container Event handling failed",
|
||||
},
|
||||
});
|
||||
|
||||
// post event handling
|
||||
switch (event) {
|
||||
.quit => break :draw,
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
container.resize(try renderer.resize());
|
||||
container.reposition(.{});
|
||||
try renderer.render(@TypeOf(container), &container);
|
||||
try renderer.flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub const panic = App.panic_handler;
|
||||
const log = std.log.scoped(.default);
|
||||
|
||||
const std = @import("std");
|
||||
const time = std.time;
|
||||
const assert = std.debug.assert;
|
||||
const zterm = @import("zterm");
|
||||
const App = zterm.App(union(enum) {
|
||||
progress: u8,
|
||||
});
|
||||
@@ -415,6 +415,7 @@ pub fn App(comptime E: type) type {
|
||||
pub const Alignment = element.Alignment(Event);
|
||||
pub const Button = element.Button(Event, Queue);
|
||||
pub const Input = element.Input(Event, Queue);
|
||||
pub const Progress = element.Progress(Event, Queue);
|
||||
pub const Scrollable = element.Scrollable(Event);
|
||||
pub const Queue = queue.Queue(Event, 256);
|
||||
};
|
||||
|
||||
177
src/element.zig
177
src/element.zig
@@ -400,7 +400,7 @@ pub fn Input(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
|
||||
queue: *Queue,
|
||||
|
||||
/// Configuration for InputField's.
|
||||
pub const Configuration = struct {
|
||||
pub const Configuration = packed struct {
|
||||
color: Color,
|
||||
|
||||
pub fn init(color: Color) @This() {
|
||||
@@ -651,6 +651,106 @@ pub fn Button(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
|
||||
return button_struct.button_fn;
|
||||
}
|
||||
|
||||
pub fn Progress(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
|
||||
// NOTE the struct is necessary, as otherwise I cannot point to the function I want to return
|
||||
const progress_struct = struct {
|
||||
pub fn progress_fn(progress_event: meta.FieldEnum(Event)) type {
|
||||
{ // check for type correctness and the associated type to use for the passed `progress_event`
|
||||
const err_msg = "Unexpected type for the associated input completion event to trigger. Only `u8` is allowed.";
|
||||
switch (@typeInfo(@FieldType(Event, @tagName(progress_event)))) {
|
||||
.int => |num| {
|
||||
if (num.signedness != .unsigned) @compileError(err_msg);
|
||||
switch (num.bits) {
|
||||
8 => {},
|
||||
else => @compileError(err_msg),
|
||||
}
|
||||
},
|
||||
else => @compileError(err_msg),
|
||||
}
|
||||
}
|
||||
return struct {
|
||||
configuration: Configuration,
|
||||
progress: u8 = 0,
|
||||
queue: *Queue,
|
||||
|
||||
pub const Configuration = packed struct {
|
||||
/// Control whether the percentage of the progress be rendered.
|
||||
percent: packed struct {
|
||||
enabled: bool = false,
|
||||
alignment: enum(u2) { left, middle, right } = .middle,
|
||||
} = .{},
|
||||
/// Foreground color to use for the progress bar.
|
||||
fg: Color,
|
||||
/// Background color to use for the progress bar.
|
||||
bg: Color,
|
||||
/// Code point to use for rendering the progress bar with.
|
||||
cp: u21 = '━',
|
||||
};
|
||||
|
||||
pub fn init(queue: *Queue, configuration: Configuration) @This() {
|
||||
return .{
|
||||
.configuration = configuration,
|
||||
.queue = queue,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn element(this: *@This()) Element(Event) {
|
||||
return .{
|
||||
.ptr = this,
|
||||
.vtable = &.{
|
||||
.handle = handle,
|
||||
.content = content,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
fn handle(ctx: *anyopaque, event: Event) !void {
|
||||
var this: *@This() = @ptrCast(@alignCast(ctx));
|
||||
// TODO should this `Element` trigger a completion event? (I don't think that this is useful?)
|
||||
switch (event) {
|
||||
progress_event => |value| {
|
||||
assert(value >= 0 and value <= 100);
|
||||
this.progress = value;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn content(ctx: *anyopaque, cells: []Cell, size: Point) !void {
|
||||
const this: *@This() = @ptrCast(@alignCast(ctx));
|
||||
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
|
||||
|
||||
const ratio: f32 = @as(f32, @floatFromInt(size.x)) / 100.0;
|
||||
const scrollbar_end_pos: usize = @intFromFloat(ratio * @as(f32, @floatFromInt(this.progress)));
|
||||
|
||||
// NOTE remain `undefined` in case percentage rendering is not enabled
|
||||
var percent_buf: [6]u8 = undefined;
|
||||
var percent_buf_len: usize = undefined;
|
||||
if (this.configuration.percent.enabled) percent_buf_len = (try std.fmt.bufPrint(&percent_buf, "[{d: >3}%]", .{this.progress})).len;
|
||||
|
||||
for (0..size.x) |idx| {
|
||||
// NOTE the progress bar is rendered at the bottom row of the `Container` taking its entire columns
|
||||
cells[((size.y - 1) * size.x) + idx] = .{
|
||||
.style = .{
|
||||
.fg = if (scrollbar_end_pos > 0 and idx <= scrollbar_end_pos) this.configuration.fg else this.configuration.bg,
|
||||
.emphasis = &.{},
|
||||
},
|
||||
.cp = if (this.configuration.percent.enabled) switch (this.configuration.percent.alignment) {
|
||||
.left => if (idx < percent_buf_len) percent_buf[idx] else this.configuration.cp,
|
||||
.middle => if (idx >= ((size.x - percent_buf_len) / 2) and idx < ((size.x - percent_buf_len) / 2) + percent_buf_len) percent_buf[percent_buf_len - (((size.x - percent_buf_len) / 2) + percent_buf_len - idx - 1) - 1] else this.configuration.cp,
|
||||
.right => if (idx >= size.x - percent_buf_len) percent_buf[percent_buf_len - ((size.x - idx + percent_buf_len - 1) % percent_buf_len) - 1] else this.configuration.cp,
|
||||
} else this.configuration.cp,
|
||||
};
|
||||
// NOTE do not write over the contents of this `Container`'s `Size`
|
||||
if (idx == cells.len - 1) break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
return progress_struct.progress_fn;
|
||||
}
|
||||
|
||||
const std = @import("std");
|
||||
const assert = std.debug.assert;
|
||||
const meta = std.meta;
|
||||
@@ -1225,3 +1325,78 @@ test "button" {
|
||||
else => false,
|
||||
});
|
||||
}
|
||||
|
||||
test "progress" {
|
||||
const allocator = std.testing.allocator;
|
||||
const event = @import("event.zig");
|
||||
const Event = event.mergeTaggedUnions(event.SystemEvent, union(enum) {
|
||||
progress: u8,
|
||||
});
|
||||
const testing = @import("testing.zig");
|
||||
const Queue = @import("queue").Queue(Event, 256);
|
||||
|
||||
const size: Point = .{
|
||||
.x = 30,
|
||||
.y = 20,
|
||||
};
|
||||
|
||||
var container: Container(Event) = try .init(allocator, .{
|
||||
.layout = .{
|
||||
.padding = .all(1),
|
||||
},
|
||||
.rectangle = .{ .fill = .white },
|
||||
}, .{});
|
||||
defer container.deinit();
|
||||
|
||||
var progress: Progress(Event, Queue)(.progress) = .init(&.{}, .{
|
||||
.percent = .{ .enabled = true },
|
||||
.fg = .green,
|
||||
.bg = .grey,
|
||||
});
|
||||
const progress_container: Container(Event) = try .init(allocator, .{}, progress.element());
|
||||
try container.append(progress_container);
|
||||
|
||||
var renderer: testing.Renderer = .init(allocator, size);
|
||||
defer renderer.deinit();
|
||||
|
||||
container.resize(size);
|
||||
container.reposition(.{});
|
||||
try renderer.render(Container(Event), &container);
|
||||
// try testing.expectEqualCells(.{}, renderer.size, @import("test/element/progress_zero.zon"), renderer.screen);
|
||||
|
||||
// test the progress of the `Element`
|
||||
try container.handle(.{
|
||||
.progress = 25,
|
||||
});
|
||||
container.resize(size);
|
||||
container.reposition(.{});
|
||||
try renderer.render(Container(Event), &container);
|
||||
// try testing.expectEqualCells(.{}, renderer.size, @import("test/element/progress_one_quarter.zon"), renderer.screen);
|
||||
|
||||
// test the progress of the `Element`
|
||||
try container.handle(.{
|
||||
.progress = 50,
|
||||
});
|
||||
container.resize(size);
|
||||
container.reposition(.{});
|
||||
try renderer.render(Container(Event), &container);
|
||||
// try testing.expectEqualCells(.{}, renderer.size, @import("test/element/progress_half.zon"), renderer.screen);
|
||||
|
||||
// test the progress of the `Element`
|
||||
try container.handle(.{
|
||||
.progress = 75,
|
||||
});
|
||||
container.resize(size);
|
||||
container.reposition(.{});
|
||||
try renderer.render(Container(Event), &container);
|
||||
// try testing.expectEqualCells(.{}, renderer.size, @import("test/element/progress_three_quarter.zon"), renderer.screen);
|
||||
|
||||
// test the progress of the `Element`
|
||||
try container.handle(.{
|
||||
.progress = 100,
|
||||
});
|
||||
container.resize(size);
|
||||
container.reposition(.{});
|
||||
try renderer.render(Container(Event), &container);
|
||||
// try testing.expectEqualCells(.{}, renderer.size, @import("test/element/progress_one_hundred.zon"), renderer.screen);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user