add(examples/layout): vertical, horizontal and grid
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s

This commit is contained in:
2025-02-21 11:31:18 +01:00
parent 69c1600eb9
commit 9dc1a4b95a
8 changed files with 369 additions and 209 deletions

View File

@@ -5,6 +5,19 @@
> [!NOTE] > [!NOTE]
> Only builds using the master version are tested to work. > Only builds using the master version are tested to work.
## Demo
Clone this repository and run `zig build --help` to see the available examples. Run a given example as follows:
```sh
zig build --release=safe -Dexample=input run
```
> [!NOTE]
> Every example application can be quitted using `ctrl+c`.
See the [wiki](https://gitea.yves-biener/yves-biener/zterm) for a showcase of the examples and the further details.
## Usage ## Usage
To add or update `zterm` as a dependency in your project run the following command: To add or update `zterm` as a dependency in your project run the following command:
@@ -24,8 +37,6 @@ const zterm: *Dependency = b.dependency("zterm", .{
exe.root_module.addImport("zterm", zterm.module("zterm")); exe.root_module.addImport("zterm", zterm.module("zterm"));
``` ```
For an example you can take a look at [build.zig](build.zig) for an example.
--- ---
## Design Goals ## Design Goals
@@ -114,9 +125,9 @@ the primary use-case for myself to create this library in the first place.
- [ ] Inline rendering (**later**) - [ ] Inline rendering (**later**)
- [ ] Examples - [ ] Examples
- [ ] Layouts - [ ] Layouts
- [ ] vertical - [x] vertical
- [ ] horizontal - [x] horizontal
- [ ] grid - [x] grid
- [ ] mixed (some sort of form) - [ ] mixed (some sort of form)
- [ ] Elements - [ ] Elements
- [ ] Button - [ ] Button

View File

@@ -5,12 +5,17 @@ pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const Examples = enum { const Examples = enum {
// elements:
input, input,
layout,
scrollable, scrollable,
// layouts:
vertical,
horizontal,
grid,
// styles:
}; };
const example = b.option(Examples, "example", "Example to build and/or run. (default: layout)") orelse .layout; const example = b.option(Examples, "example", "Example to build and/or run. (default: vertical)") orelse .vertical;
const options = b.addOptions(); const options = b.addOptions();
options.addOption(Examples, "example", example); options.addOption(Examples, "example", example);
@@ -29,7 +34,9 @@ pub fn build(b: *std.Build) void {
}); });
lib.addImport("code_point", zg.module("code_point")); lib.addImport("code_point", zg.module("code_point"));
// Examples.Input //--- Examples ---
// elements:
const input = b.addExecutable(.{ const input = b.addExecutable(.{
.name = "input", .name = "input",
.root_source_file = b.path("examples/input.zig"), .root_source_file = b.path("examples/input.zig"),
@@ -38,29 +45,49 @@ pub fn build(b: *std.Build) void {
}); });
input.root_module.addImport("zterm", lib); input.root_module.addImport("zterm", lib);
// Examples.Layout
const layout = b.addExecutable(.{
.name = "layout",
.root_source_file = b.path("examples/layout.zig"),
.target = target,
.optimize = optimize,
});
layout.root_module.addImport("zterm", lib);
// Examples.Scrollable
const scrollable = b.addExecutable(.{ const scrollable = b.addExecutable(.{
.name = "scrollable", .name = "scrollable",
.root_source_file = b.path("examples/scrollable.zig"), .root_source_file = b.path("examples/elements/scrollable.zig"),
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
}); });
scrollable.root_module.addImport("zterm", lib); scrollable.root_module.addImport("zterm", lib);
// layouts:
const vertical = b.addExecutable(.{
.name = "vertical",
.root_source_file = b.path("examples/layouts/vertical.zig"),
.target = target,
.optimize = optimize,
});
vertical.root_module.addImport("zterm", lib);
const horizontal = b.addExecutable(.{
.name = "horizontal",
.root_source_file = b.path("examples/layouts/horizontal.zig"),
.target = target,
.optimize = optimize,
});
horizontal.root_module.addImport("zterm", lib);
const grid = b.addExecutable(.{
.name = "grid",
.root_source_file = b.path("examples/layouts/grid.zig"),
.target = target,
.optimize = optimize,
});
grid.root_module.addImport("zterm", lib);
// mapping of user selected example to compile step // mapping of user selected example to compile step
const exe = switch (example) { const exe = switch (example) {
// elements:
.input => input, .input => input,
.layout => layout,
.scrollable => scrollable, .scrollable => scrollable,
// layouts:
.vertical => vertical,
.horizontal => horizontal,
.grid => grid,
// styles:
}; };
b.installArtifact(exe); b.installArtifact(exe);

View File

@@ -1,189 +0,0 @@
const std = @import("std");
const zterm = @import("zterm");
const App = zterm.App(union(enum) {
send: []u21,
});
const log = std.log.scoped(.default);
pub const InputField = struct {
// TODO: I would need the following features:
// - current position of the input (i.e. a cursor)
// - gnu readline keybindings
// - truncate inputs?
input: std.ArrayList(u21),
/// The thread safe `App.Event` queue used to send events to the application's event loop.
queue: *App.Queue,
pub fn init(allocator: std.mem.Allocator, queue: *App.Queue) @This() {
return .{
.input = .init(allocator),
.queue = queue,
};
}
pub fn deinit(this: *@This()) void {
this.input.deinit();
}
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
// example function to handle events for a `Container`
fn handle(ctx: *anyopaque, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.key => |key| {
if (key.isAscii()) try this.input.append(key.cp);
if (key.eql(.{ .cp = zterm.input.Enter }) or key.eql(.{ .cp = zterm.input.KpEnter }))
this.queue.push(.{ .send = try this.input.toOwnedSlice() });
if (key.eql(.{ .cp = zterm.input.Backspace }) or key.eql(.{ .cp = zterm.input.Delete }) or key.eql(.{ .cp = zterm.input.KpDelete }))
_ = this.input.pop();
},
else => {},
}
}
// example function to render contents for a `Container`
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
if (this.input.items.len == 0) return;
const row = size.rows / 2;
const col: u16 = 5;
for (this.input.items, 0..) |cp, idx| {
cells[(row * size.cols) + col + idx].style.fg = .black;
cells[(row * size.cols) + col + idx].cp = cp;
// NOTE: do not write over the contents of this `Container`'s `Size`
if ((row * size.cols) + col + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
// TODO: maybe create own allocator as some sort of arena allocator to have consistent memory usage
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .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 element_wrapper: InputField = .init(allocator, &app.queue);
defer element_wrapper.deinit();
const element = element_wrapper.element();
var container = try App.Container.init(allocator, .{
.border = .{
.separator = .{
.enabled = true,
.line = .double,
},
},
.layout = .{
.gap = 2,
.padding = .all(5),
.direction = .vertical,
},
}, .{});
var box = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.layout = .{
.gap = 1,
.direction = .horizontal,
.padding = .vertical(1),
},
}, .{});
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
}, .{}));
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
}, element));
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
}, .{}));
try container.append(box);
try container.append(try App.Container.init(allocator, .{
.border = .{
.color = .light_blue,
.sides = .vertical,
},
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
defer container.deinit(); // also de-initializes the children
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
switch (event) {
.init => {
try container.handle(event);
continue; // do not render
},
.quit => break,
.resize => |size| try renderer.resize(size),
.key => |key| {
if (key.eql(.{ .cp = 'q' })) app.quit();
if (key.eql(.{ .cp = 'n', .mod = .{ .ctrl = true } })) {
try app.interrupt();
defer app.start() catch @panic("could not start app event loop");
// FIX: the rendering is afterwards incorrect (wrong state of the double buffered renderer?)
var child = std.process.Child.init(&.{"hx"}, allocator);
_ = child.spawnAndWait() catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Spawning $EDITOR failed",
},
});
}
},
.send => |input| {
// NOTE: as the input in owned by the caller, this means that it still needs to be freed
defer allocator.free(input);
log.info("accepted user input: {any}", .{input});
},
// 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 => {},
}
// NOTE: returned errors should be propagated back to the application
container.handle(event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}
}

109
examples/layouts/grid.zig Normal file
View File

@@ -0,0 +1,109 @@
const std = @import("std");
const zterm = @import("zterm");
const App = zterm.App(union(enum) {});
const log = std.log.scoped(.default);
const QuitText = struct {
const text = "Press ctrl+c to quit.";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
// no handle function required
.vtable = &.{ .content = content },
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
const row: u16 = 2;
const col: u16 = size.cols / 2 -| (@as(u16, @truncate(text.len)) / 2);
const anchor = (row * size.cols) + 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.GeneralPurposeAllocator(.{}) = .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 quit_text: QuitText = .{};
const element = quit_text.element();
var container = try App.Container.init(allocator, .{
.border = .{ .separator = .{ .enabled = true } },
.layout = .{
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .horizontal,
},
}, element);
for (0..3) |_| {
var column = try App.Container.init(allocator, .{
.border = .{ .separator = .{ .enabled = true } },
.layout = .{
.direction = .vertical,
},
}, .{});
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try container.append(column);
}
defer container.deinit(); // also de-initializes the children
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 => {},
}
// NOTE: returned errors should be propagated back to the application
container.handle(event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}
}

View File

@@ -0,0 +1,101 @@
const std = @import("std");
const zterm = @import("zterm");
const App = zterm.App(union(enum) {});
const log = std.log.scoped(.default);
const QuitText = struct {
const text = "Press ctrl+c to quit.";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
// no handle function required
.vtable = &.{ .content = content },
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
const row: u16 = 2;
const col: u16 = size.cols / 2 -| (@as(u16, @truncate(text.len)) / 2);
const anchor = (row * size.cols) + 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.GeneralPurposeAllocator(.{}) = .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 quit_text: QuitText = .{};
const element = quit_text.element();
var container = try App.Container.init(allocator, .{
.border = .{},
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .horizontal,
},
}, element);
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
defer container.deinit(); // also de-initializes the children
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 => {},
}
// NOTE: returned errors should be propagated back to the application
container.handle(event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}
}

View File

@@ -0,0 +1,101 @@
const std = @import("std");
const zterm = @import("zterm");
const App = zterm.App(union(enum) {});
const log = std.log.scoped(.default);
const QuitText = struct {
const text = "Press ctrl+c to quit.";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
// no handle function required
.vtable = &.{ .content = content },
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
const row: u16 = 2;
const col: u16 = size.cols / 2 -| (@as(u16, @truncate(text.len)) / 2);
const anchor = (row * size.cols) + 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.GeneralPurposeAllocator(.{}) = .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 quit_text: QuitText = .{};
const element = quit_text.element();
var container = try App.Container.init(allocator, .{
.border = .{},
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .vertical,
},
}, element);
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}, .{}));
defer container.deinit(); // also de-initializes the children
try app.start();
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 => {},
}
// NOTE: returned errors should be propagated back to the application
container.handle(event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}
}