8 Commits

Author SHA1 Message Date
1ad7bf0d48 WIP: exec element with initial implementation
Problem is that the main application actually does not create a pty and
instead uses the current one (for better compatability for ssh based
hosting).

The current problem is the fact that the child process should not
take over (and never give back too) the input / output handling of the
current pts. Such that both applications can receive inputs accordingly
(in best case actually controlled by the main application).
2025-07-12 20:26:47 +02:00
df78c7d6eb mod: bump zg dependency version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m19s
2025-07-11 22:38:47 +02:00
66b3a77805 feat(container): negative layout padding
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Has been cancelled
Negative paddings use the current size to calculate the padding from
the opposite orientation. For a given dimension (horizontal or vertical)
if the size is `30` a padding of `5` would be equivalent to a padding
of `-25`. This enables to describe the size of the container using
the padding property of the `Layout` and gives users more freedom to
describe different layouts.
2025-07-11 22:33:32 +02:00
b401b5ece8 lint(container): style
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m41s
2025-07-07 23:08:06 +02:00
9f33c902ee mod(container): cleanup and highlight points for improvement
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m42s
2025-07-06 00:42:00 +02:00
9f29ac6a77 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
2025-07-05 18:29:49 +02:00
f775a6ab2d formatting
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 13s
2025-06-30 22:53:05 +02:00
a39cee7ccb feat(element/button): add builtin Element implementation for buttons 2025-06-30 22:52:27 +02:00
9 changed files with 775 additions and 107 deletions

View File

@@ -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",

View File

@@ -37,8 +37,8 @@
// internet connectivity.
.dependencies = .{
.zg = .{
.url = "git+https://codeberg.org/atman/zg#0b05141b033043c5f7bcd72048a48eef6531ea6c",
.hash = "zg-0.14.0-oGqU3KEFswIffnDu8eAE2XlhzwcfgjwtM6akIc5L7cEV",
.url = "git+https://codeberg.org/atman/zg#9427a9e53aaa29ee071f4dcb35b809a699d75aa9",
.hash = "zg-0.14.1-oGqU3IQ_tALZIiBN026_NTaPJqU-Upm8P_C7QED2Rzm8",
},
},
.paths = .{

View File

@@ -79,54 +79,29 @@ pub fn main() !void {
}, quit_text.element());
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
var nested_container: App.Container = try .init(allocator, .{
.layout = .{
.direction = .vertical,
.separator = .{
.enabled = true,
},
},
}, .{});
var inner_container: App.Container = try .init(allocator, .{
.layout = .{
.direction = .vertical,
var environment = try std.process.getEnvMap(allocator);
defer environment.deinit();
var editor: App.Exec = .init(
allocator,
&.{
"tty",
},
&environment,
&app.queue,
);
defer editor.deinit();
try container.append(try App.Container.init(allocator, .{
.border = .{
.color = .light_blue,
.sides = .all,
},
}, .{});
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .blue,
},
.size = .{
.grow = .horizontal,
.dim = .{ .y = 5 },
.dim = .{ .x = 100 },
},
}, .{}));
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .red,
},
.size = .{
.grow = .horizontal,
.dim = .{ .y = 5 },
},
}, .{}));
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .green,
},
}, .{}));
try nested_container.append(inner_container);
try nested_container.append(try .init(allocator, .{
.size = .{
.grow = .horizontal,
.dim = .{ .y = 1 },
},
}, .{}));
try container.append(nested_container);
}, editor.element()));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.size = .{
@@ -138,6 +113,11 @@ pub fn main() !void {
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
var process_in: std.ArrayListUnmanaged(u8) = .empty;
defer process_in.deinit(allocator);
var process_out: std.ArrayListUnmanaged(u8) = .empty;
defer process_out.deinit(allocator);
// event loop
while (true) {
const event = app.nextEvent();
@@ -145,23 +125,7 @@ pub fn main() !void {
// pre event handling
switch (event) {
.key => |key| {
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
if (key.eql(.{ .cp = 'n', .mod = .{ .ctrl = true } })) {
try app.interrupt();
renderer.size = .{}; // reset size, such that next resize will cause a full re-draw!
defer app.start() catch @panic("could not start app event loop");
var child = std.process.Child.init(&.{"hx"}, allocator);
_ = child.spawnAndWait() catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Spawning $EDITOR failed",
},
});
continue;
}
},
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
// NOTE errors could be displayed in another container in case one was received, etc. to provide the user with feedback
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},

View File

@@ -89,6 +89,8 @@ pub fn main() !void {
var clickable: Clickable = .{ .queue = &app.queue };
const element = clickable.element();
var button: App.Button(.accept) = .init(&app.queue, .init(.default, "Button"));
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
@@ -98,6 +100,7 @@ pub fn main() !void {
defer container.deinit();
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .light_grey } }, element));
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .black } }, button.element()));
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
@@ -110,9 +113,8 @@ pub fn main() !void {
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.click => |button| {
log.info("Clicked with mouse using Button: {s}", .{button});
},
.click => |b| log.info("Clicked with mouse using Button: {s}", .{b}),
.accept => log.info("Clicked built-in button using the mouse", .{}),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
@@ -145,4 +147,5 @@ const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(union(enum) {
click: [:0]const u8,
accept,
});

View 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,
});

View File

@@ -288,12 +288,8 @@ pub fn App(comptime E: type) type {
.x = px -| 1,
.y = py -| 1,
.kind = blk: {
if (motion and button != Mouse.Button.none) {
break :blk .drag;
}
if (motion and button == Mouse.Button.none) {
break :blk .motion;
}
if (motion and button != Mouse.Button.none) break :blk .drag;
if (motion and button == Mouse.Button.none) break :blk .motion;
if (sequence[sequence.len - 1] == 'm') break :blk .release;
break :blk .press;
},
@@ -417,8 +413,11 @@ pub fn App(comptime E: type) type {
pub const Container = @import("container.zig").Container(Event);
pub const Element = element.Element(Event);
pub const Alignment = element.Alignment(Event);
pub const Scrollable = element.Scrollable(Event);
pub const Button = element.Button(Event, Queue);
pub const Exec = element.Exec(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);
};
}

View File

@@ -195,6 +195,33 @@ pub const Rectangle = packed struct {
}, &container, @import("test/container/rectangle_with_parent_padding.zon"));
}
test "fill color padding to show parent fill (negative padding)" {
const event = @import("event.zig");
const testing = @import("testing.zig");
var container: Container(event.SystemEvent) = try .init(std.testing.allocator, .{
.layout = .{
.padding = .{
.top = -18,
.bottom = -18,
.left = -28,
.right = -28,
},
},
.rectangle = .{ .fill = .green },
}, .{});
try container.append(try .init(std.testing.allocator, .{
.rectangle = .{ .fill = .white },
}, .{}));
try container.append(try .init(std.testing.allocator, .{}, .{}));
defer container.deinit();
try testing.expectContainerScreen(.{
.y = 20,
.x = 30,
}, &container, @import("test/container/rectangle_with_parent_padding.zon"));
}
test "fill color spacer with padding" {
const event = @import("event.zig");
const testing = @import("testing.zig");
@@ -293,23 +320,23 @@ pub const Layout = packed struct {
direction: enum(u1) { horizontal, vertical } = .horizontal,
/// Padding outside of the child elements
padding: packed struct {
top: u16 = 0,
bottom: u16 = 0,
left: u16 = 0,
right: u16 = 0,
top: i16 = 0,
bottom: i16 = 0,
left: i16 = 0,
right: i16 = 0,
/// Create a padding with equivalent padding in all four directions.
pub fn all(padding: u16) @This() {
pub fn all(padding: i16) @This() {
return .{ .top = padding, .bottom = padding, .left = padding, .right = padding };
}
/// Create a padding with equivalent padding in the left and right directions; others directions remain the default value.
pub fn horizontal(padding: u16) @This() {
pub fn horizontal(padding: i16) @This() {
return .{ .left = padding, .right = padding };
}
/// Create a padding with equivalent padding in the top and bottom directions; others directions remain the default value.
pub fn vertical(padding: u16) @This() {
pub fn vertical(padding: i16) @This() {
return .{ .top = padding, .bottom = padding };
}
} = .{},
@@ -326,6 +353,11 @@ pub const Layout = packed struct {
} = .line,
} = .{},
/// Calculate the absolute offset for the provided `padding` if it is negative to get the absolute padding for the given `size`.
pub fn getAbsolutePadding(padding: i16, size: u16) u16 {
return if (padding >= 0) @intCast(padding) else size -| @as(u16, @intCast(-padding));
}
pub fn content(this: @This(), comptime C: type, cells: []Cell, origin: Point, size: Point, children: []const C) void {
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
@@ -566,6 +598,7 @@ pub fn Container(comptime Event: type) type {
size: Point,
properties: Properties,
element: Element,
// TODO this should be renamed to `children`
elements: std.ArrayList(@This()),
/// Properties for each `Container` to configure their layout,
@@ -593,10 +626,8 @@ pub fn Container(comptime Event: type) type {
};
}
pub fn deinit(this: *@This()) void {
for (this.elements.items) |*element| {
element.deinit();
}
pub fn deinit(this: *const @This()) void {
for (this.elements.items) |*element| element.deinit();
this.elements.deinit();
}
@@ -610,8 +641,8 @@ pub fn Container(comptime Event: type) type {
this.element.reposition(origin);
var offset = origin.add(.{
.x = layout.padding.left,
.y = layout.padding.top,
.x = Layout.getAbsolutePadding(layout.padding.left, this.size.x),
.y = Layout.getAbsolutePadding(layout.padding.top, this.size.y),
});
const sides = this.properties.border.sides;
@@ -643,8 +674,8 @@ pub fn Container(comptime Event: type) type {
};
if (this.elements.items.len > 0) switch (layout.direction) {
.horizontal => size.x += layout.padding.left + layout.padding.right,
.vertical => size.y += layout.padding.top + layout.padding.bottom,
.horizontal => size.x += Layout.getAbsolutePadding(layout.padding.left, this.size.x) + Layout.getAbsolutePadding(layout.padding.right, this.size.x),
.vertical => size.y += Layout.getAbsolutePadding(layout.padding.top, this.size.y) + Layout.getAbsolutePadding(layout.padding.bottom, this.size.y),
};
const sides = this.properties.border.sides;
@@ -692,16 +723,16 @@ pub fn Container(comptime Event: type) type {
fn grow_resize(this: *@This(), max_size: Point) void {
const layout = this.properties.layout;
var remainder = switch (layout.direction) {
.horizontal => max_size.x -| (layout.padding.left + layout.padding.right),
.vertical => max_size.y -| (layout.padding.top + layout.padding.bottom),
.horizontal => max_size.x -| (Layout.getAbsolutePadding(layout.padding.left, this.size.x) + Layout.getAbsolutePadding(layout.padding.right, this.size.x)),
.vertical => max_size.y -| (Layout.getAbsolutePadding(layout.padding.top, this.size.y) + Layout.getAbsolutePadding(layout.padding.bottom, this.size.y)),
};
remainder -|= layout.gap * @as(u16, @truncate(this.elements.items.len -| 1));
if (layout.separator.enabled) remainder -|= @as(u16, @truncate(this.elements.items.len -| 1));
var available = switch (layout.direction) {
.horizontal => max_size.y -| (layout.padding.top + layout.padding.bottom),
.vertical => max_size.x -| (layout.padding.left + layout.padding.right),
.horizontal => max_size.y -| (Layout.getAbsolutePadding(layout.padding.top, this.size.y) + Layout.getAbsolutePadding(layout.padding.bottom, this.size.y)),
.vertical => max_size.x -| (Layout.getAbsolutePadding(layout.padding.left, this.size.x) + Layout.getAbsolutePadding(layout.padding.right, this.size.x)),
};
const sides = this.properties.border.sides;
@@ -773,6 +804,7 @@ pub fn Container(comptime Event: type) type {
for (this.elements.items) |child| {
if (child.properties.size.grow == .fixed) continue;
switch (layout.direction) {
.horizontal => if (child.properties.size.grow == .vertical) continue,
.vertical => if (child.properties.size.grow == .horizontal) continue,
@@ -794,10 +826,8 @@ pub fn Container(comptime Event: type) type {
size_to_correct = @min(size_to_correct, remainder / growable_children);
var overflow: u16 = 0;
if (size_to_correct == 0 and remainder > 0) {
// there is some overflow
overflow = remainder;
}
if (size_to_correct == 0 and remainder > 0) overflow = remainder;
for (this.elements.items) |*child| {
const child_size = switch (layout.direction) {
.horizontal => child.size.x,
@@ -838,6 +868,7 @@ pub fn Container(comptime Event: type) type {
pub fn resize(this: *@This(), size: Point) void {
// NOTE assume that this function is only called for the root `Container`
this.size = size;
const fit_size = this.fit_resize();
// if (fit_size.y > size.y or fit_size.x > size.x) @panic("error: cannot render in available space");
switch (this.properties.size.grow) {
@@ -855,7 +886,7 @@ pub fn Container(comptime Event: type) type {
this.grow_resize(this.size);
}
pub fn handle(this: *@This(), event: Event) !void {
pub fn handle(this: *const @This(), event: Event) !void {
switch (event) {
.mouse => |mouse| if (mouse.in(this.origin, this.size)) {
// the element receives the mouse event with relative position
@@ -873,11 +904,12 @@ pub fn Container(comptime Event: type) type {
}
}
pub fn content(this: *const @This()) ![]const Cell {
pub fn content(this: *const @This()) ![]Cell {
if (this.size.x == 0 or this.size.y == 0) return Error.TooSmall;
const cells = try this.allocator.alloc(Cell, @as(usize, this.size.x) * @as(usize, this.size.y));
@memset(cells, .{});
errdefer this.allocator.free(cells);
@memset(cells, .{});
this.properties.layout.content(@This(), cells, this.origin, this.size, this.elements.items);
this.properties.border.content(cells, this.size);

View File

@@ -182,6 +182,7 @@ pub fn Scrollable(Event: type) type {
configuration: Configuration,
pub const Configuration = packed struct {
// TODO the scrollbar bool and the color should be in their own struct using `enabled` and `color` inside of the struct to be more consistent with other `Configuration` structs
scrollbar: bool,
color: Color = .default,
x_axis: bool = false,
@@ -281,7 +282,6 @@ pub fn Scrollable(Event: type) type {
const size = container.size;
const origin = container.origin;
const contents = try container.content();
defer container.allocator.free(contents);
const anchor = (@as(usize, origin.y) * @as(usize, container_size.x)) + @as(usize, origin.x);
@@ -294,6 +294,8 @@ pub fn Scrollable(Event: type) type {
if (contents.len == idx) break :blk;
}
}
// free immediately
container.allocator.free(contents);
for (container.elements.items) |child| try render_container(child, cells, size);
}
@@ -306,13 +308,7 @@ pub fn Scrollable(Event: type) type {
const offset_y: usize = if (this.configuration.y_axis) 1 else 0;
const container_size = this.container.size;
const container_cells = try this.container.allocator.alloc(Cell, @as(usize, container_size.x) * @as(usize, container_size.y));
{
const container_cells_const = try this.container.content();
defer this.container.allocator.free(container_cells_const);
assert(container_cells_const.len == @as(usize, container_size.x) * @as(usize, container_size.y));
@memcpy(container_cells, container_cells_const);
}
const container_cells = try this.container.content();
for (this.container.elements.items) |child| try render_container(child, container_cells, container_size);
@@ -370,9 +366,8 @@ pub fn Input(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
const input_struct = struct {
pub fn input_fn(accept_event: meta.FieldEnum(Event)) type {
const event_type: enum { ascii, utf8 } = blk: { // check for type correctness and the associated type to use for the passed `accept_event`
const t = @FieldType(Event, @tagName(accept_event));
const err_msg = "Unexpected type for the associated input completion event to trigger. Only `[]u8` or `[]u21` are allowed.";
switch (@typeInfo(t)) {
switch (@typeInfo(@FieldType(Event, @tagName(accept_event)))) {
.pointer => |pointer| {
if (pointer.size != .slice) @compileError(err_msg);
switch (@typeInfo(pointer.child)) {
@@ -401,7 +396,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() {
@@ -574,6 +569,418 @@ pub fn Input(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
return input_struct.input_fn;
}
pub fn Button(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 button_struct = struct {
pub fn button_fn(accept_event: meta.FieldEnum(Event)) type {
{ // check for type correctness and the associated type to use for the passed `accept_event`
const err_msg = "Unexpected type for the associated input completion event to trigger. Only `void` is allowed.";
switch (@typeInfo(@FieldType(Event, @tagName(accept_event)))) {
.void => |_| {},
else => @compileError(err_msg),
}
}
return struct {
queue: *Queue,
configuration: Configuration,
/// Configuration for InputField's.
pub const Configuration = struct {
color: Color,
text: []const u8,
pub fn init(color: Color, text: []const u8) @This() {
return .{
.color = color,
.text = text,
};
}
};
pub fn init(queue: *Queue, configuration: Configuration) @This() {
return .{
.queue = queue,
.configuration = configuration,
};
}
pub fn element(this: *@This()) Element(Event) {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
fn handle(ctx: *anyopaque, event: Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
// TODO should this also support key presses to accept?
.mouse => |mouse| if (mouse.button == .left and mouse.kind == .release) this.queue.push(accept_event),
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));
// NOTE center text in the middle of the available cell slice
const row = size.y / 2 -| (this.configuration.text.len / 2);
const col = size.x / 2 -| (this.configuration.text.len / 2);
const anchor = (row * size.x) + col;
for (0.., this.configuration.text) |idx, cp| {
cells[anchor + idx].style.fg = this.configuration.color;
cells[anchor + idx].style.emphasis = &.{.bold};
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
}
};
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 {
const 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;
}
pub fn Exec(Event: type, Queue: type) type {
// TODO
// - wrap own process into command structure
// https://github.com/rockorager/libvaxis/blob/main/src/widgets/terminal/Command.zig
// - create tty / pty and setup process to use that tty / pty
// https://github.com/rockorager/libvaxis/blob/main/src/tty.zig
// https://github.com/rockorager/libvaxis/blob/main/src/widgets/terminal/Pty.zig
// - read & write contents from & to tty / pty for outputs & inputs
return struct {
allocator: std.mem.Allocator,
command: Command,
pty: Pty,
queue: *Queue,
pub const Pty = struct {
pty: std.posix.fd_t,
tty: std.posix.fd_t,
pub fn init() !@This() {
const p = try std.posix.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true }, 0);
errdefer std.posix.close(p);
// unlockpt
var n: c_uint = 0;
if (std.posix.system.ioctl(p, std.posix.T.IOCSPTLCK, @intFromPtr(&n)) != 0) return error.IoctlError;
// ptsname
if (std.posix.system.ioctl(p, std.posix.T.IOCGPTN, @intFromPtr(&n)) != 0) return error.IoctlError;
var buf: [16]u8 = undefined;
const sname = try std.fmt.bufPrint(&buf, "/dev/pts/{d}", .{n});
std.log.debug("pts: {s}", .{sname});
const t = try std.posix.open(sname, .{ .ACCMODE = .RDWR, .NOCTTY = true }, 0);
return .{
.pty = p,
.tty = t,
};
}
pub fn deinit(this: *@This()) void {
std.posix.close(this.pty);
std.posix.close(this.tty);
}
pub fn resize(this: *@This(), size: Point) !void {
const ws: std.posix.winsize = .{
.col = size.x,
.row = size.y,
.xpixel = 0,
.ypixel = 0,
};
if (std.posix.system.ioctl(this.pty, std.posix.T.IOCSWINSZ, @intFromPtr(&ws)) != 0) return error.SetWinsizeError;
}
};
pub const Command = struct {
argv: []const []const u8,
working_directory: ?[]const u8,
pid: ?std.posix.pid_t = null,
environment: *const std.process.EnvMap,
pty: Pty,
queue: *Queue,
handler: bool = false,
const SignalHandler = struct {
context: *anyopaque,
callback: *const fn (ctx: *anyopaque, pid: std.posix.pid_t) void,
};
pub fn spawn(this: *@This(), allocator: std.mem.Allocator) !void {
const argv = try allocator.allocSentinel(?[*:0]const u8, this.argv.len, null);
for (this.argv, 0..) |arg, i| argv[i] = (try allocator.dupeZ(u8, arg)).ptr;
// FIX environment is leaking memory
const environment = blk: {
const count: usize = this.environment.count();
const buffer = try allocator.allocSentinel(?[*:0]u8, count, null);
var i: usize = 0;
var it = this.environment.iterator();
while (it.next()) |pair| {
buffer[i] = try std.fmt.allocPrintZ(allocator, "{s}={s}", .{ pair.key_ptr.*, pair.value_ptr.* });
i += 1;
}
std.debug.assert(i == count);
break :blk buffer;
};
const pid = try std.posix.fork();
if (pid == 0) {
// child
_ = std.os.linux.setsid();
// if (std.posix.system.ioctl(this.pty.tty, std.posix.T.IOCSCTTY, std.posix.STDIN_FILENO) != 0) return error.IoctlError;
// TODO user input / output should not be stdin / stdout, but instead a different abstraction in between, allowing
// for simultan input handling of inner commands and `Container`'s and `Element`'s
// set up io
try std.posix.dup2(this.pty.tty, std.posix.STDIN_FILENO);
try std.posix.dup2(this.pty.tty, std.posix.STDOUT_FILENO);
try std.posix.dup2(this.pty.tty, std.posix.STDERR_FILENO);
std.posix.close(this.pty.tty);
if (this.pty.pty > 2) std.posix.close(this.pty.pty);
if (this.working_directory) |wd| try std.posix.chdir(wd);
const err = std.posix.execvpeZ(argv.ptr[0].?, argv.ptr, environment);
_ = err catch {};
// free resources (no longer required)
allocator.free(environment);
}
// parent
this.pid = @intCast(pid);
// register handler for sig child
if (!this.handler) {
defer this.handler = true;
var winch_act = std.posix.Sigaction{
.handler = .{ .handler = @This().handleSigChild },
.mask = std.posix.sigemptyset(),
.flags = 0,
};
std.posix.sigaction(std.posix.SIG.CHLD, &winch_act, null);
try registerSigChild(.{
.context = this,
.callback = @This().exitCallback,
});
}
}
var chld_handler: ?SignalHandler = null;
fn registerSigChild(handler: SignalHandler) !void {
if (chld_handler) |_| @panic("Cannot register another CHLD handler.");
chld_handler = handler;
}
fn handleSigChild(_: c_int) callconv(.C) void {
const result = std.posix.waitpid(-1, 0);
if (chld_handler) |handler| handler.callback(handler.context, result.pid);
}
fn exitCallback(ctx: *anyopaque, pid: std.posix.pid_t) void {
const this: *@This() = @ptrCast(@alignCast(ctx));
// fire exited event with corresponding pid to free
if (this.pid) |command_pid| if (pid == command_pid) this.queue.push(.{ .exited = pid });
}
pub fn kill(this: *@This()) void {
if (this.pid) |pid| {
std.posix.kill(pid, std.posix.SIG.TERM) catch {};
this.pid = null;
}
}
};
pub fn init(allocator: std.mem.Allocator, argv: []const []const u8, environment: *const std.process.EnvMap, queue: *Queue) @This() {
const pty = Pty.init() catch @panic("failed to initialize PTY");
return .{
.allocator = allocator,
.command = .{
.argv = argv,
.pty = pty,
.environment = environment,
.queue = queue,
.working_directory = null,
},
.pty = pty,
.queue = queue,
};
}
pub fn deinit(this: *@This()) void {
this.command.kill();
this.pty.deinit();
}
pub fn element(this: *@This()) Element(Event) {
return .{
.ptr = this,
.vtable = &.{
.resize = resize,
.handle = handle,
.content = content,
},
};
}
fn resize(ctx: *anyopaque, size: Point) void {
const this: *@This() = @ptrCast(@alignCast(ctx));
this.pty.resize(size) catch {};
}
fn handle(ctx: *anyopaque, event: Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
// TODO pass through inputs accordingly
// - key events
// - mouse events
switch (event) {
.init => try this.command.spawn(this.allocator),
.exited => |pid| if (this.command.pid) |command_pid| {
if (command_pid == pid) {
// this command has completed!
std.log.debug("command finished: {any}", .{pid});
}
},
else => {},
}
}
fn content(ctx: *anyopaque, cells: []Cell, size: Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
var buf: [8 * 1024]u8 = undefined;
const length = try std.posix.read(this.pty.pty, &buf);
for (1.., buf[0..length]) |idx, c| cells[idx + size.x].cp = c;
// TODO support tui applications which render raw!
// -> directly apply the raw ansi codes
// -> or translate them into the `Cell` structure
// TODO map contents of tty / pty to cells
// - content (Cell.cp)
// - style (Cell.style)
}
};
}
const std = @import("std");
const assert = std.debug.assert;
const meta = std.meta;
@@ -1101,3 +1508,125 @@ test "input element" {
else => unreachable,
}
}
test "button" {
const allocator = std.testing.allocator;
const event = @import("event.zig");
const Event = event.mergeTaggedUnions(event.SystemEvent, union(enum) {
accept,
});
const testing = @import("testing.zig");
const Queue = @import("queue").Queue(Event, 256);
const size: Point = .{
.x = 30,
.y = 20,
};
var queue: Queue = .{};
var container: Container(Event) = try .init(allocator, .{}, .{});
defer container.deinit();
var button: Button(Event, Queue)(.accept) = .init(&queue, .init(.default, "Button"));
const button_container: Container(Event) = try .init(allocator, .{
.rectangle = .{ .fill = .blue },
}, button.element());
try container.append(button_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/button.zon"), renderer.screen);
// test the accepting of the `Element`
try container.handle(.{
.mouse = .{
.x = 5,
.y = 3,
.button = .left,
.kind = .release,
},
});
try std.testing.expect(switch (queue.pop()) {
.accept => true,
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);
}

View File

@@ -24,6 +24,8 @@ pub const SystemEvent = union(enum) {
/// Focus event for mouse interaction
/// TODO this should instead be a union with a `Size` to derive which container / element the focus meant for
focus: bool,
/// Exit event for a completed `Exec` with the associated pid. Fired and handled by `Exec` `Element`s.
exited: std.posix.pid_t,
};
pub fn mergeTaggedUnions(comptime A: type, comptime B: type) type {