42 Commits

Author SHA1 Message Date
0b7d032b11 tag: 0.2.0
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m15s
2025-03-27 21:43:02 +01:00
7e20dd73d9 mod: add missing inline function attribute
Correct example to use the actual `zterm.Error` type accordingly.
2025-03-27 21:41:18 +01:00
182dec6065 release: 0.1.0
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 21s
2025-03-13 19:50:49 +01:00
54af974c2b mod(container): make reposition public and split from resize
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m3s
2025-03-13 19:48:31 +01:00
dddc09b4ce mod(container/element): remove origin: Point argument from Element.content function
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m12s
Renamed `Container.contents` to `Container.content` to be in line with
the corresponding `Element` function name. This has also been done for
the properties structs used by the `Container`.
2025-03-11 07:52:35 +01:00
adda53c5a9 add(test): container size with fixed and growable container children
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-03-10 22:07:34 +01:00
5c1d61eefd rem(element): unnecessary debug loging
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m20s
2025-03-10 21:44:18 +01:00
54c7e19939 fix(container): growth options to dynamically size Containers
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 29s
2025-03-06 22:31:00 +01:00
5457e91b37 fix(container/grow_size): respect vertical / horizontal provided dimensions 2025-03-06 22:07:39 +01:00
79016f39b2 fix(container/grow_size): children should never grow larger then parents
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 29s
2025-03-06 17:56:13 +01:00
2b9ab1e0fb fix(example/styles): provide necessary size for text display through the element
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 31s
This could also be done through the `resize` function interface of the
`Element` or the corresponding `Container` from the outside (as done in
this example - as the size is know at compile-time).
2025-03-05 23:22:06 +01:00
315cd8d23e fix(layout): remove upper bound of while loop
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 29s
The upper loop was incorrect and therefore removed to create correct
layouts. I should be able to calculate the bound correctly, but for
now).
2025-03-05 23:14:54 +01:00
e3551fa624 add(sizing): grow configuration
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m14s
Currently the 'grid' and 'mixed' examples are not working yet.
2025-03-05 22:53:28 +01:00
9ec335cad8 fix(lint): correct spelling error
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 49s
2025-03-04 23:01:28 +01:00
466e00c16c fix(element/scrollable): support deriving Container size of scrollable
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 13s
2025-03-04 21:54:07 +01:00
fc72cf4abb ref(container): split size and position calculations
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 34s
2025-03-04 19:53:28 +01:00
65d7546efd fix(testing): apply refactor to test implementation
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 27s
2025-03-04 14:54:51 +01:00
ec22e68e8c ref(event): remove .resize and replace with recursize method calls
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 40s
This also means that currently the dynamic resizing through the app's
detached thread is not working, as it cannot send size updates. The
examples have been overhauled to still implement intermediate mode
applications accordingly.
2025-03-04 14:52:19 +01:00
43cdc46853 fix(input/mouse): correct boundary check for mouse position inside of given origin and size
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Has been cancelled
2025-03-04 14:51:26 +01:00
591b990087 ref(event): split Size into two Points (one for the size and one for the anchor / origin)
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 39s
2025-03-04 00:04:56 +01:00
91ac6241f4 doc: correct TODO, NOTE and FIX comment statements
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 48s
2025-03-03 21:49:11 +01:00
edefc80759 mod(container/border): render horizontal borders across entire Container
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 27s
2025-03-02 23:03:00 +01:00
4145ff497b fix(elements/scrollable): nested container rendering
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 2m45s
2025-03-02 22:27:26 +01:00
bec0cf2987 fix(container): check border sides configurations before trying to create borders
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 28s
2025-03-01 20:58:34 +01:00
e2fe884925 chors: update build file configurations
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 28s
2025-03-01 17:57:28 +01:00
caee008d50 test: streamline examples with quit texts
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 24s
Improve some examples to provide visual feedback, i.e. for the button
exmample, with fixes to make them compilable with the `Scrollable`
element changes.
2025-03-01 17:12:28 +01:00
af443c6bbf test(elements/scrollable): remove redundance from test code
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 28s
2025-03-01 16:24:10 +01:00
ae9cd08b15 add(error): introduce zterm.Error containing all zterm errors with their corresponding description
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 28s
2025-03-01 15:19:42 +01:00
91794a0197 add(build): .fingerprint property for most recent zig version
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 49s
2025-03-01 15:15:06 +01:00
8a7ce78aaf feat(container): introduce fixed_size property for fixed sizing of Containers
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 42s
Moved min_size property from `Container` to the `Scrollable` element,
where it is only used anyway.
2025-03-01 11:56:14 +01:00
35ebe31008 doc: correct example used in README
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 18s
2025-02-28 15:58:46 +01:00
c28fcd26c1 fix(container/layout): integer overflows by casting to usize
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m5s
2025-02-28 15:55:10 +01:00
3b6848f845 fix(container): rendering scrollable elements with separators
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 23s
Added corresponding test cases to test the corresponding rendering of
scrollable elements.
2025-02-27 17:02:16 +01:00
53b69f034c mod(size): rename merge function to add; new max function
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m6s
2025-02-27 14:17:19 +01:00
54ce697e91 fix(lint): typo
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 47s
2025-02-26 21:54:29 +01:00
8f16435f30 test(container): rectangle color filling
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m4s
2025-02-26 21:04:28 +01:00
ca14bc6106 fix(container): positioning; move separator options to layout struct
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 22s
Added corresponding test cases for padding, borders and corresponding
seperators.
2025-02-26 18:21:55 +01:00
a293ef46da test(container): add missing zon test configurations
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 46s
2025-02-25 20:41:35 +01:00
c66401d941 testing(container): border separator test cases
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 40s
Currently the test case with both a border and separators for two
children is failing to render the separators.
2025-02-25 20:39:18 +01:00
ad4186e1f8 test(container): move test template for zon file creation to wiki
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-02-25 19:04:21 +01:00
8c130a40d7 test(container): correct color
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m15s
2025-02-25 18:46:06 +01:00
9a3bc3dbf7 fix(lint): exclude zon files located in src/test 2025-02-25 18:45:13 +01:00
50 changed files with 1584 additions and 685 deletions

View File

@@ -18,7 +18,7 @@ jobs:
with:
version: master
- name: Lint check
run: zig fmt --check .
run: zig fmt --check --exclude src/test .
- name: Spell checking
uses: crate-ci/typos@v1.25.0
with:

View File

@@ -10,7 +10,7 @@
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
zig build --release=safe -Dexample=demo run
```
> [!TIP]

View File

@@ -5,6 +5,7 @@ pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});
const Examples = enum {
all,
demo,
// elements:
button,
@@ -22,7 +23,7 @@ pub fn build(b: *std.Build) void {
errors,
};
const example = b.option(Examples, "example", "Example to build and/or run. (default: demo)") orelse .demo;
const example = b.option(Examples, "example", "Example to build and/or run. (default: all)") orelse .all;
const options = b.addOptions();
options.addOption(Examples, "example", example);
@@ -153,6 +154,19 @@ pub fn build(b: *std.Build) void {
.palette => palette,
// error handling:
.errors => errors,
else => blk: {
b.installArtifact(button);
b.installArtifact(input);
b.installArtifact(scrollable);
b.installArtifact(vertical);
b.installArtifact(horizontal);
b.installArtifact(grid);
b.installArtifact(mixed);
b.installArtifact(text);
b.installArtifact(palette);
b.installArtifact(errors);
break :blk demo;
},
};
b.installArtifact(exe);

View File

@@ -6,16 +6,29 @@
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "zterm",
.name = .zterm,
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
// package is first created, and then *never changes*. This allows
// unambiguous detection of one package being an updated version of
// another.
//
// When forking a Zig project, this id should be regenerated (delete the
// field and run `zig build`) if the upstream project is still maintained.
// Otherwise, the fork is *hostile*, attempting to take control over the
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0xf10b37e210a619d7, // Changing this has security and trust implications.
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
.version = "0.2.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.15.0-dev.56+d0911786c",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
@@ -29,11 +42,9 @@
},
},
.paths = .{
"LICENSE",
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

View File

@@ -13,20 +13,20 @@ const QuitText = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
const y = 2;
const x = size.x / 2 -| (text.len / 2);
const anchor = (y * size.x) + x;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -35,7 +35,7 @@ const QuitText = struct {
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
// 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", .{});
@@ -47,15 +47,22 @@ pub fn main() !void {
var quit_text: QuitText = .{};
// TODO: what should the demo application do?
// TODO what should the demo application do?
// - some sort of chat? -> write messages and have them displayed in a scrollable array at the right hand side?
// - on the left some buttons?
var box = try App.Container.init(allocator, .{
.border = .{
.color = .blue,
.sides = .all,
},
.layout = .{
.gap = 1,
.padding = .vertical(2),
.direction = .vertical,
},
.size = .{
.dim = .{ .y = 90 },
},
.min_size = .{ .cols = 50 },
}, .{});
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
@@ -68,16 +75,12 @@ pub fn main() !void {
}, .{}));
defer box.deinit();
var scrollable: App.Scrollable = .{
.container = box,
};
var scrollable: App.Scrollable = .{ .container = box };
var container = try App.Container.init(allocator, .{
.border = .{
.separator = .{ .enabled = true },
},
.layout = .{
.gap = 2,
.separator = .{ .enabled = true },
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .horizontal,
},
@@ -89,9 +92,15 @@ pub fn main() !void {
.color = .light_blue,
.sides = .all,
},
.size = .{
.dim = .{ .x = 100 },
},
}, .{}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.size = .{
.dim = .{ .x = 30 },
},
}, .{}));
defer container.deinit(); // also de-initializes the children
@@ -103,10 +112,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.key => |key| {
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
@@ -123,18 +130,28 @@ pub fn main() !void {
continue;
}
},
// NOTE: errors could be displayed in another container in case one was received, etc. to provide the user with feedback
// 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
// 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",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -7,10 +7,37 @@ const App = zterm.App(union(enum) {
const log = std.log.scoped(.default);
pub const Clickable = struct {
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;
std.debug.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;
}
}
};
const Clickable = struct {
const text = "Press me";
queue: *App.Queue,
color: zterm.Color = .black,
pub fn element(this: *@This()) App.Element {
return .{
@@ -25,24 +52,32 @@ pub const Clickable = struct {
fn handle(ctx: *anyopaque, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.mouse => |mouse| this.queue.push(.{ .click = @tagName(mouse.button) }),
.mouse => |mouse| if (mouse.button == .left and mouse.kind == .release) {
var value = @intFromEnum(this.color);
value += 1;
value %= 17;
if (value == 0) value = 1;
this.color = @enumFromInt(value);
this.queue.push(.{ .click = @tagName(mouse.button) });
},
else => {},
}
}
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));
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = size.rows / 2 -| (text.len / 2);
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
const row = size.y / 2 -| (text.len / 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 = .black;
cells[anchor + idx].style.fg = this.color;
cells[anchor + idx].style.emphasis = &.{.bold};
cells[anchor + idx].cp = cp;
// NOTE: do not write over the contents of this `Container`'s `Size`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -63,10 +98,12 @@ pub fn main() !void {
var clickable: Clickable = .{ .queue = &app.queue };
const element = clickable.element();
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{ .padding = .all(5) },
}, .{});
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .light_grey } }, element));
@@ -79,10 +116,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.click => |button| {
log.info("Clicked with mouse using Button: {s}", .{button});
@@ -98,6 +133,15 @@ pub fn main() !void {
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -7,7 +7,33 @@ const App = zterm.App(union(enum) {
const log = std.log.scoped(.default);
pub const InputField = struct {
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;
std.debug.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;
}
}
};
const InputField = struct {
input: std.ArrayList(u21),
queue: *App.Queue,
@@ -48,21 +74,21 @@ pub const InputField = struct {
}
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
if (this.input.items.len == 0) return;
const row = 1;
const col = 1;
const anchor = (row * size.cols) + col;
const anchor = (row * size.x) + col;
for (this.input.items, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .black;
cells[anchor + idx].cp = cp;
// NOTE: do not write over the contents of this `Container`'s `Size`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -83,12 +109,14 @@ pub fn main() !void {
var input_field: InputField = .init(allocator, &app.queue);
defer input_field.deinit();
var quit_text: QuitText = .{};
const element = input_field.element();
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{ .padding = .all(5) },
}, .{});
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .light_grey } }, element));
@@ -101,10 +129,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.accept => |input| {
defer allocator.free(input);
@@ -121,6 +147,15 @@ pub fn main() !void {
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -6,7 +6,33 @@ const App = zterm.App(union(enum) {});
const log = std.log.scoped(.default);
pub const HelloWorldText = packed struct {
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;
std.debug.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;
}
}
};
const HelloWorldText = packed struct {
const text = "Hello World";
pub fn element(this: *@This()) App.Element {
@@ -16,18 +42,21 @@ pub const HelloWorldText = packed struct {
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
// NOTE: error should only be returned here in case an in-recoverable exception has occurred
const row = size.rows / 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
const row = size.y / 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (0.., text) |idx, char| {
cells[anchor + idx].style.fg = .black;
cells[anchor + idx].cp = char;
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;
}
}
};
@@ -35,7 +64,7 @@ pub const HelloWorldText = packed struct {
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
// TODO maybe create own allocator as some sort of arena allocator to have consistent memory usage
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
defer {
const deinit_status = gpa.deinit();
@@ -52,34 +81,55 @@ pub fn main() !void {
var element_wrapper: HelloWorldText = .{};
const element = element_wrapper.element();
var quit_text: QuitText = .{};
var top_box = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.layout = .{
.gap = 1,
.gap = 2,
.separator = .{
.enabled = true,
},
.direction = .vertical,
.padding = .vertical(1),
},
.min_size = .{ .rows = 50 },
}, .{});
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
.size = .{
.dim = .{ .y = 30 },
},
}, .{}));
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
.size = .{
.dim = .{ .y = 5 },
},
}, element));
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .light_green },
.size = .{
.dim = .{ .y = 2 },
},
}, .{}));
defer top_box.deinit();
var bottom_box = try App.Container.init(allocator, .{
.border = .{ .separator = .{ .enabled = true } },
.rectangle = .{ .fill = .blue },
.border = .{
.sides = .all,
.color = .blue,
},
.layout = .{
.separator = .{
.enabled = true,
.color = .red,
},
.direction = .vertical,
.padding = .vertical(1),
},
.min_size = .{ .rows = 30 },
.size = .{
.dim = .{ .y = 30 },
},
}, .{});
try bottom_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
@@ -93,25 +143,23 @@ pub fn main() !void {
defer bottom_box.deinit();
var container = try App.Container.init(allocator, .{
.border = .{
.layout = .{
.gap = 2,
.separator = .{
.enabled = true,
.line = .double,
},
},
.layout = .{
.gap = 2,
.padding = .all(5),
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .vertical,
},
}, .{});
}, quit_text.element());
defer container.deinit();
// place empty container containing the element of the scrollable Container.
var scrollable_top: App.Scrollable = .init(top_box);
var scrollable_top: App.Scrollable = .{ .container = top_box };
try container.append(try App.Container.init(allocator, .{}, scrollable_top.element()));
var scrollable_bottom: App.Scrollable = .init(bottom_box);
var scrollable_bottom: App.Scrollable = .{ .container = bottom_box };
try container.append(try App.Container.init(allocator, .{}, scrollable_bottom.element()));
try app.start();
@@ -122,10 +170,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 }),
else => {},
@@ -137,6 +183,16 @@ pub fn main() !void {
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -12,20 +12,20 @@ const QuitText = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -38,20 +38,20 @@ const InfoText = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -64,31 +64,30 @@ const ErrorNotification = struct {
return .{ .ptr = this, .vtable = &.{ .handle = handle, .content = content } };
}
pub fn handle(ctx: *anyopaque, event: App.Event) !void {
fn handle(ctx: *anyopaque, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.key => |key| if (!key.isAscii()) return error.UnsupportedKey,
.resize => |_| {},
.key => |key| if (!key.isAscii()) return zterm.Error.TooSmall,
.err => |err| this.msg = err.msg,
else => {},
}
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
if (this.msg) |msg| {
const row = size.rows -| 2;
const col = size.cols -| 2 -| msg.len;
const anchor = (row * size.cols) + col;
const row = size.y -| 2;
const col = size.x -| 2 -| msg.len;
const anchor = (row * size.x) + col;
for (msg, 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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
@@ -131,10 +130,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 }),
else => {},
@@ -146,6 +143,16 @@ pub fn main() !void {
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -15,20 +15,20 @@ const QuitText = struct {
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -50,16 +50,16 @@ pub fn main() !void {
const element = quit_text.element();
var container = try App.Container.init(allocator, .{
.border = .{ .separator = .{ .enabled = true } },
.layout = .{
.separator = .{ .enabled = true },
.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 = .{
.separator = .{ .enabled = true },
.direction = .vertical,
},
}, .{});
@@ -84,23 +84,31 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
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
// 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
// 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",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -15,20 +15,20 @@ const QuitText = struct {
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -76,23 +76,31 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
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
// 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
// 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",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -15,20 +15,20 @@ const QuitText = struct {
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -53,13 +53,12 @@ pub fn main() !void {
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .horizontal,
},
}, element);
for (0..3) |i| {
var column = try App.Container.init(allocator, .{
.border = .{ .separator = .{ .enabled = true } },
.layout = .{
.separator = .{ .enabled = true },
.direction = if (i > 0) .vertical else .horizontal,
},
}, .{});
@@ -71,7 +70,12 @@ pub fn main() !void {
.rectangle = .{ .fill = .yellow },
}, .{}));
} else {
try column.append(try App.Container.init(allocator, .{}, .{}));
try column.append(try App.Container.init(allocator, .{
.size = .{
.dim = .{ .y = 4 },
.grow = .horizontal,
},
}, .{}));
}
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
@@ -88,23 +92,31 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
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
// 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
// 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",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -15,20 +15,20 @@ const QuitText = struct {
};
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -75,23 +75,31 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
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
// 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
// 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",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -12,20 +12,20 @@ const QuitText = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -56,7 +56,6 @@ pub fn main() !void {
var box = try App.Container.init(allocator, .{
.layout = .{ .direction = .horizontal },
.min_size = .{ .cols = 3 * std.meta.fields(zterm.Color).len }, // ensure enough columns to render all colors -> scrollable otherwise
}, .{});
defer box.deinit();
@@ -64,7 +63,7 @@ pub fn main() !void {
if (comptime field.value == 0) continue; // zterm.Color.default == 0 -> skip
try box.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = @enumFromInt(field.value) } }, .{}));
}
var scrollable: App.Scrollable = .init(box);
var scrollable: App.Scrollable = .{ .container = box };
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
try app.start();
@@ -74,10 +73,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 }),
else => {},
@@ -89,6 +86,16 @@ pub fn main() !void {
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -12,20 +12,20 @@ const QuitText = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
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`
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
@@ -38,10 +38,10 @@ const TextStyles = struct {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Point) !void {
@setEvalBranchQuota(50000);
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
var row: usize = 0;
var col: usize = 0;
@@ -56,9 +56,9 @@ const TextStyles = struct {
// witouth any emphasis
for (text) |cp| {
cells[(row * size.cols) + col].style.bg = @enumFromInt(bg_field.value);
cells[(row * size.cols) + col].style.fg = @enumFromInt(fg_field.value);
cells[(row * size.cols) + col].cp = cp;
cells[(row * size.x) + col].style.bg = @enumFromInt(bg_field.value);
cells[(row * size.x) + col].style.fg = @enumFromInt(fg_field.value);
cells[(row * size.x) + col].cp = cp;
col += 1;
}
@@ -68,10 +68,10 @@ const TextStyles = struct {
const emphasis: zterm.Style.Emphasis = @enumFromInt(emp_field.value);
for (text) |cp| {
cells[(row * size.cols) + col].style.bg = @enumFromInt(bg_field.value);
cells[(row * size.cols) + col].style.fg = @enumFromInt(fg_field.value);
cells[(row * size.cols) + col].style.emphasis = &.{emphasis};
cells[(row * size.cols) + col].cp = cp;
cells[(row * size.x) + col].style.bg = @enumFromInt(bg_field.value);
cells[(row * size.x) + col].style.fg = @enumFromInt(fg_field.value);
cells[(row * size.x) + col].style.emphasis = &.{emphasis};
cells[(row * size.x) + col].cp = cp;
col += 1;
}
}
@@ -109,14 +109,16 @@ pub fn main() !void {
var box = try App.Container.init(allocator, .{
.layout = .{ .direction = .vertical },
.min_size = .{
.rows = (std.meta.fields(zterm.Color).len - 1) * (std.meta.fields(zterm.Color).len - 2),
.cols = std.meta.fields(zterm.Style.Emphasis).len * TextStyles.text.len,
}, // ensure enough rows and/or columns to render all text styles -> scrollable otherwise
.size = .{
.dim = .{
.x = std.meta.fields(zterm.Style.Emphasis).len * TextStyles.text.len,
.y = (std.meta.fields(zterm.Color).len - 1) * (std.meta.fields(zterm.Color).len - 2),
},
},
}, text_styles.element());
defer box.deinit();
var scrollable: App.Scrollable = .init(box);
var scrollable: App.Scrollable = .{ .container = box };
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
try app.start();
@@ -126,10 +128,8 @@ pub fn main() !void {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.init => continue,
.quit => break,
.resize => |size| try renderer.resize(size),
.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 }),
else => {},
@@ -141,6 +141,16 @@ pub fn main() !void {
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
try renderer.resize();
container.resize(renderer.size);
container.reposition(.{});
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}

View File

@@ -11,7 +11,7 @@ const isTaggedUnion = event.isTaggedUnion;
const Mouse = input.Mouse;
const Key = input.Key;
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
const log = std.log.scoped(.app);
@@ -51,7 +51,6 @@ pub fn App(comptime E: type) type {
quit_event: std.Thread.ResetEvent,
termios: ?std.posix.termios = null,
attached_handler: bool = false,
prev_size: Size,
pub const SignalHandler = struct {
context: *anyopaque,
@@ -64,7 +63,6 @@ pub fn App(comptime E: type) type {
.quit_event = .{},
.termios = null,
.attached_handler = false,
.prev_size = .{},
};
pub fn start(this: *@This()) !void {
@@ -99,11 +97,6 @@ pub fn App(comptime E: type) type {
try terminal.enterAltScreen();
try terminal.hideCursor();
try terminal.enableMouseSupport();
// send initial size afterwards
const size = terminal.getTerminalSize();
this.postEvent(.{ .resize = size });
this.prev_size = size;
}
pub fn interrupt(this: *@This()) !void {
@@ -148,11 +141,8 @@ pub fn App(comptime E: type) type {
fn winsizeCallback(ptr: *anyopaque) void {
const this: *@This() = @ptrCast(@alignCast(ptr));
const size = terminal.getTerminalSize();
if (size.cols != this.prev_size.cols or size.rows != this.prev_size.rows) {
this.postEvent(.{ .resize = size });
this.prev_size = size;
}
_ = this;
// this.postEvent(.{ .size = terminal.getTerminalSize() });
}
var winch_handler: ?SignalHandler = null;
@@ -174,11 +164,11 @@ pub fn App(comptime E: type) type {
// thread to read user inputs
var buf: [256]u8 = undefined;
while (true) {
// FIX: I still think that there is a race condition (I'm just waiting 'long' enough)
// FIX I still think that there is a race condition (I'm just waiting 'long' enough)
this.quit_event.timedWait(20 * std.time.ns_per_ms) catch {
// FIX: in case the queue is full -> the next user input should panic and quit the application? because something seems to clock up the event queue
// FIX in case the queue is full -> the next user input should panic and quit the application? because something seems to clock up the event queue
const read_bytes = try terminal.read(buf[0..]);
// TODO: `break` should not terminate the reading of the user inputs, but instead only the received faulty input!
// TODO `break` should not terminate the reading of the user inputs, but instead only the received faulty input!
// escape key presses
if (buf[0] == 0x1b and read_bytes > 1) {
switch (buf[1]) {
@@ -273,7 +263,7 @@ pub fn App(comptime E: type) type {
};
this.postEvent(.{ .key = key });
},
// TODO: focus usage? should this even be in the default event system?
// TODO focus usage? should this even be in the default event system?
'I' => this.postEvent(.{ .focus = true }),
'O' => this.postEvent(.{ .focus = false }),
'M', 'm' => {
@@ -302,8 +292,8 @@ pub fn App(comptime E: type) type {
const mouse: Mouse = .{
.button = button,
.col = px -| 1,
.row = py -| 1,
.x = px -| 1,
.y = py -| 1,
.kind = blk: {
if (motion and button != Mouse.Button.none) {
break :blk .drag;
@@ -334,19 +324,15 @@ pub fn App(comptime E: type) type {
if (std.mem.eql(u8, "48", ps)) {
// in band window resize
// CSI 48 ; height ; width ; height_pix ; width_pix t
const height_char = iter.next() orelse break;
const width_char = iter.next() orelse break;
const height_char = iter.next() orelse break;
// TODO: only post the event if the size has changed?
// because there might be too many resize events (which force a re-draw of the entire screen)
const size: Size = .{
.rows = std.fmt.parseUnsigned(u16, height_char, 10) catch break,
.cols = std.fmt.parseUnsigned(u16, width_char, 10) catch break,
};
if (size.cols != this.prev_size.cols or size.rows != this.prev_size.rows) {
this.postEvent(.{ .resize = size });
this.prev_size = size;
}
_ = width_char;
_ = height_char;
// this.postEvent(.{ .size = .{
// .x = std.fmt.parseUnsigned(u16, width_char, 10) catch break,
// .y = std.fmt.parseUnsigned(u16, height_char, 10) catch break,
// } });
}
},
'u' => {
@@ -361,7 +347,7 @@ pub fn App(comptime E: type) type {
else => {},
}
},
// TODO: parse corresponding codes
// TODO parse corresponding codes
// 0x5B => parseCsi(input, &self.buf), // CSI see https://github.com/rockorager/libvaxis/blob/main/src/Parser.zig
else => {},
}

View File

@@ -4,7 +4,7 @@ const Style = @import("style.zig");
pub const Cell = @This();
style: Style = .{ .emphasis = &.{} },
// TODO: embrace `zg` dependency more due to utf-8 encoding
// TODO embrace `zg` dependency more due to utf-8 encoding
cp: u21 = ' ',
pub fn eql(this: Cell, other: Cell) bool {

View File

@@ -18,7 +18,7 @@ pub const Color = enum(u8) {
magenta,
cyan,
white,
// TODO: add further colors as described in https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b # Color / Graphics Mode - 256 Colors
// TODO add further colors as described in https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b # Color / Graphics Mode - 256 Colors
pub inline fn write(this: Color, writer: anytype, comptime coloring: enum { fg, bg, ul }) !void {
if (this == .default) {

File diff suppressed because it is too large Load Diff

View File

@@ -92,7 +92,7 @@ pub const bg_rgb_legacy = "\x1b[48;2;{d};{d};{d}m";
pub const ul_rgb_legacy = "\x1b[58;2;{d};{d};{d}m";
// Underlines
pub const ul_off = "\x1b[24m"; // NOTE: this could be \x1b[4:0m but is not as widely supported
pub const ul_off = "\x1b[24m"; // NOTE this could be \x1b[4:0m but is not as widely supported
pub const ul_single = "\x1b[4m";
pub const ul_double = "\x1b[4:2m";
pub const ul_curly = "\x1b[4:3m";

View File

@@ -1,13 +1,11 @@
//! Interface for Element's which describe the contents of a `Container`.
const std = @import("std");
const s = @import("size.zig");
const input = @import("input.zig");
const Container = @import("container.zig").Container;
const Cell = @import("cell.zig");
const Mouse = input.Mouse;
const Position = s.Position;
const Size = s.Size;
const Point = @import("point.zig").Point;
pub fn Element(Event: type) type {
return struct {
@@ -15,12 +13,26 @@ pub fn Element(Event: type) type {
vtable: *const VTable = &.{},
pub const VTable = struct {
resize: ?*const fn (ctx: *anyopaque, size: Point) void = null,
reposition: ?*const fn (ctx: *anyopaque, origin: Point) void = null,
handle: ?*const fn (ctx: *anyopaque, event: Event) anyerror!void = null,
content: ?*const fn (ctx: *anyopaque, cells: []Cell, size: Size) anyerror!void = null,
content: ?*const fn (ctx: *anyopaque, cells: []Cell, size: Point) anyerror!void = null,
};
/// Resize the corresponding `Element` with the given *size*.
pub inline fn resize(this: @This(), size: Point) void {
if (this.vtable.resize) |resize_fn|
resize_fn(this.ptr, size);
}
/// Reposition the corresponding `Element` with the given *origin*.
pub inline fn reposition(this: @This(), origin: Point) void {
if (this.vtable.reposition) |reposition_fn|
reposition_fn(this.ptr, origin);
}
/// Handle the received event. The event is one of the user provided
/// events or a system event, with the exception of the `.resize`
/// events or a system event, with the exception of the `.size`
/// `Event` as every `Container` already handles that event.
///
/// In case of user errors this function should return an error. This
@@ -32,14 +44,21 @@ pub fn Element(Event: type) type {
}
/// Write content into the `cells` of the `Container`. The associated
/// `cells` slice has the size of (`size.cols * size.rows`). The
/// `cells` slice has the size of (`size.x * size.y`). The
/// renderer will know where to place the contents on the screen.
///
/// This function should only fail with an error if the error is
/// non-recoverable (i.e. an allocation error, system error, etc.).
/// Otherwise user specific errors should be caught using the `handle`
/// function before the rendering of the `Container` happens.
pub inline fn content(this: @This(), cells: []Cell, size: Size) !void {
/// # Note
///
/// - Caller owns `cells` slice and ensures that the size usually by assertion:
/// ```zig
/// std.debug.assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
/// ```
///
/// - This function should only fail with an error if the error is
/// non-recoverable (i.e. an allocation error, system error, etc.).
/// Otherwise user specific errors should be caught using the `handle`
/// function before the rendering of the `Container` happens.
pub inline fn content(this: @This(), cells: []Cell, size: Point) !void {
if (this.vtable.content) |content_fn|
try content_fn(this.ptr, cells, size);
}
@@ -50,63 +69,64 @@ pub fn Scrollable(Event: type) type {
return struct {
/// `Size` of the actual contents where the anchor and the size is
/// representing the size and location on screen.
size: Size = .{},
size: Point = .{},
/// `Size` of the `Container` content that is scrollable and mapped to
/// the *size* of the `Scrollable` `Element`.
container_size: Size = .{},
container_size: Point = .{},
/// Anchor of the viewport of the scrollable `Container`.
anchor: Position = .{},
/// The actual container, that is scrollable.
anchor: Point = .{},
/// The actual `Container`, that is scrollable.
container: Container(Event),
pub fn element(this: *@This()) Element(Event) {
return .{
.ptr = this,
.vtable = &.{
.resize = resize,
.reposition = reposition,
.handle = handle,
.content = content,
},
};
}
pub fn init(container: Container(Event)) @This() {
return .{ .container = container };
fn resize(ctx: *anyopaque, size: Point) void {
const this: *@This() = @ptrCast(@alignCast(ctx));
this.size = size;
// TODO scrollbar space - depending on configuration and only if necessary?
this.container.resize(this.size);
this.container_size = this.container.size;
}
fn reposition(ctx: *anyopaque, _: Point) void {
const this: *@This() = @ptrCast(@alignCast(ctx));
this.container.reposition(.{});
}
fn handle(ctx: *anyopaque, event: Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.resize => |size| {
this.size = size;
// TODO: scrollbar space - depending on configuration and only if necessary?
const min_size = this.container.minSize();
this.container_size = .{
.anchor = size.anchor,
.cols = @max(min_size.cols, size.cols),
.rows = @max(min_size.rows, size.rows),
};
try this.container.handle(.{ .resize = this.container_size });
},
// TODO: other means to scroll except with the mouse? (i.e. Ctrl-u/d, k/j, etc.?)
// TODO other means to scroll except with the mouse? (i.e. Ctrl-u/d, k/j, etc.?)
.mouse => |mouse| switch (mouse.button) {
Mouse.Button.wheel_up => if (this.container_size.rows > this.size.rows) {
this.anchor.row -|= 1;
Mouse.Button.wheel_up => if (this.container_size.y > this.size.y) {
this.anchor.y -|= 1;
},
Mouse.Button.wheel_down => if (this.container_size.rows > this.size.rows) {
const max_anchor_row = this.container_size.rows -| this.size.rows;
this.anchor.row = @min(this.anchor.row + 1, max_anchor_row);
Mouse.Button.wheel_down => if (this.container_size.y > this.size.y) {
const max_origin_y = this.container_size.y -| this.size.y;
this.anchor.y = @min(this.anchor.y + 1, max_origin_y);
},
Mouse.Button.wheel_left => if (this.container_size.cols > this.size.cols) {
this.anchor.col -|= 1;
Mouse.Button.wheel_left => if (this.container_size.x > this.size.x) {
this.anchor.x -|= 1;
},
Mouse.Button.wheel_right => if (this.container_size.cols > this.size.cols) {
const max_anchor_col = this.container_size.cols -| this.size.cols;
this.anchor.col = @min(this.anchor.col + 1, max_anchor_col);
Mouse.Button.wheel_right => if (this.container_size.x > this.size.x) {
const max_anchor_x = this.container_size.x -| this.size.x;
this.anchor.x = @min(this.anchor.x + 1, max_anchor_x);
},
else => try this.container.handle(.{
.mouse = .{
.col = mouse.col + this.anchor.col,
.row = mouse.row + this.anchor.row,
.x = mouse.x + this.anchor.x,
.y = mouse.y + this.anchor.y,
.button = mouse.button,
.kind = mouse.kind,
},
@@ -116,48 +136,209 @@ pub fn Scrollable(Event: type) type {
}
}
fn content(ctx: *anyopaque, cells: []Cell, size: Size) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, this.size.cols) * @as(usize, this.size.rows));
fn render_container(container: Container(Event), cells: []Cell, container_size: Point) !void {
const size = container.size;
const origin = container.origin;
const contents = try container.content();
defer container.allocator.free(contents);
const container_size = this.container.size;
const container_cells = try this.container.allocator.alloc(Cell, @as(usize, container_size.cols) * @as(usize, container_size.rows));
{
const container_cells_const = try this.container.contents();
defer this.container.allocator.free(container_cells_const);
std.debug.assert(container_cells_const.len == @as(usize, container_size.cols) * @as(usize, container_size.rows));
@memcpy(container_cells, container_cells_const);
}
const anchor = (@as(usize, origin.y) * @as(usize, container_size.x)) + @as(usize, origin.x);
for (this.container.elements.items) |*e| {
const e_size = e.size;
const element_cells = try e.contents();
defer e.allocator.free(element_cells);
var idx: usize = 0;
blk: for (0..size.y) |row| {
for (0..size.x) |col| {
cells[anchor + (row * container_size.x) + col] = contents[idx];
idx += 1;
const anchor = (@as(usize, e_size.anchor.row -| container_size.anchor.row) * @as(usize, container_size.cols)) +
@as(usize, e_size.anchor.col -| container_size.anchor.col);
var idx: usize = 0;
blk: for (0..e_size.rows) |row| {
for (0..e_size.cols) |col| {
const cell = element_cells[idx];
idx += 1;
container_cells[anchor + (row * container_size.cols) + col] = cell;
if (element_cells.len == idx) break :blk;
}
if (contents.len == idx) break :blk;
}
}
const anchor = (@as(usize, this.anchor.row) * @as(usize, container_size.cols)) + @as(usize, this.anchor.col);
// TODO: render scrollbar according to configuration!
for (0..size.rows) |row| {
for (0..size.cols) |col| {
cells[(row * size.cols) + col] = container_cells[anchor + (row * container_size.cols) + col];
for (container.elements.items) |child| try render_container(child, cells, size);
}
fn content(ctx: *anyopaque, cells: []Cell, size: Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, this.size.x) * @as(usize, this.size.y));
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);
std.debug.assert(container_cells_const.len == @as(usize, container_size.x) * @as(usize, container_size.y));
@memcpy(container_cells, container_cells_const);
}
for (this.container.elements.items) |child| try render_container(child, container_cells, container_size);
const anchor = (@as(usize, this.anchor.y) * @as(usize, container_size.x)) + @as(usize, this.anchor.x);
// TODO render scrollbar according to configuration!
for (0..size.y) |row| {
for (0..size.x) |col| {
cells[(row * size.x) + col] = container_cells[anchor + (row * container_size.x) + col];
}
}
this.container.allocator.free(container_cells);
}
};
}
// TODO nested scrollable `Container`s?'
// TODO reaction only for when the event is actually pushed to the corresponding `Container` rendered container
test "scrollable vertical" {
const event = @import("event.zig");
const testing = @import("testing.zig");
const allocator = std.testing.allocator;
const size: Point = .{
.x = 30,
.y = 20,
};
var box: Container(event.SystemEvent) = try .init(allocator, .{
.border = .{
.sides = .all,
.color = .red,
},
.layout = .{
.separator = .{
.enabled = true,
.color = .red,
},
.direction = .vertical,
.padding = .all(1),
},
.size = .{
.dim = .{ .y = size.y + 15 },
},
}, .{});
try box.append(try .init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
try box.append(try .init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
defer box.deinit();
var scrollable: Scrollable(event.SystemEvent) = .{ .container = box };
var container: Container(event.SystemEvent) = try .init(allocator, .{
.border = .{
.color = .green,
.sides = .vertical,
},
}, scrollable.element());
defer container.deinit();
var renderer: testing.Renderer = .init(allocator, size);
defer renderer.deinit();
container.resize(size);
container.reposition(.{});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.vertical.top.zon"), renderer.screen);
// scroll down 15 times (exactly to the end)
for (0..15) |_| try container.handle(.{
.mouse = .{
.button = .wheel_down,
.kind = .press,
.x = 5,
.y = 5,
},
});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.vertical.bottom.zon"), renderer.screen);
// further scrolling down will not change anything
try container.handle(.{
.mouse = .{
.button = .wheel_down,
.kind = .press,
.x = 5,
.y = 5,
},
});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.vertical.bottom.zon"), renderer.screen);
}
test "scrollable horizontal" {
const event = @import("event.zig");
const testing = @import("testing.zig");
const allocator = std.testing.allocator;
const size: Point = .{
.x = 30,
.y = 20,
};
var box: Container(event.SystemEvent) = try .init(allocator, .{
.border = .{
.sides = .all,
.color = .red,
},
.layout = .{
.separator = .{
.enabled = true,
.color = .red,
},
.direction = .horizontal,
.padding = .all(1),
},
.size = .{
.dim = .{ .x = size.x + 15 },
},
}, .{});
try box.append(try .init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
try box.append(try .init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
defer box.deinit();
var scrollable: Scrollable(event.SystemEvent) = .{ .container = box };
var container: Container(event.SystemEvent) = try .init(allocator, .{
.border = .{
.color = .green,
.sides = .horizontal,
},
}, scrollable.element());
defer container.deinit();
var renderer: testing.Renderer = .init(allocator, size);
defer renderer.deinit();
container.resize(size);
container.reposition(.{});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.horizontal.left.zon"), renderer.screen);
// scroll right 15 times (exactly to the end)
for (0..15) |_| try container.handle(.{
.mouse = .{
.button = .wheel_right,
.kind = .press,
.x = 5,
.y = 5,
},
});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.horizontal.right.zon"), renderer.screen);
// further scrolling right will not change anything
try container.handle(.{
.mouse = .{
.button = .wheel_right,
.kind = .press,
.x = 5,
.y = 5,
},
});
try renderer.render(Container(event.SystemEvent), &container);
try testing.expectEqualCells(.{}, renderer.size, @import("test/element/scrollable.horizontal.right.zon"), renderer.screen);
}

4
src/error.zig Normal file
View File

@@ -0,0 +1,4 @@
pub const Error = error{
/// Thrown when a `Container` is too small to be rendered in the current screen part.
TooSmall,
};

View File

@@ -6,12 +6,12 @@ const terminal = @import("terminal.zig");
const Key = input.Key;
const Mouse = input.Mouse;
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
/// System events available to every `zterm.App`
pub const SystemEvent = union(enum) {
/// Initialize event, which is send once at the beginning of the event loop and before the first render loop
/// TODO: not sure if this is necessary or if there is an actual usecase for this - for now it will remain
/// TODO not sure if this is necessary or if there is an actual usecase for this - for now it will remain
init,
/// Quit event to signify the end of the event loop (rendering should stop afterwards)
quit,
@@ -21,14 +21,12 @@ pub const SystemEvent = union(enum) {
/// associated error message
msg: []const u8,
},
/// Resize event emitted by the terminal to derive the `Size` of the current terminal the application is rendered in
resize: Size,
/// Input key event received from the user
key: Key,
/// Mouse input event
mouse: Mouse,
/// Focus event for mouse interaction
/// TODO: this should instead be a union with a `Size` to derive which container / element the focus meant for
/// TODO this should instead be a union with a `Size` to derive which container / element the focus meant for
focus: bool,
};

View File

@@ -1,11 +1,11 @@
//! Input module for `zterm`. Contains structs to represent key events and mouse events.
const std = @import("std");
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
pub const Mouse = packed struct {
col: u16,
row: u16,
x: u16,
y: u16,
button: Button,
kind: Kind,
@@ -35,9 +35,9 @@ pub const Mouse = packed struct {
return std.meta.eql(this, other);
}
pub fn in(this: @This(), size: Size) bool {
return this.col >= size.anchor.col and this.col <= size.cols + size.anchor.col and
this.row >= size.anchor.row and this.row <= size.rows + size.anchor.row;
pub fn in(this: @This(), origin: Point, size: Point) bool {
return this.x >= origin.x and this.x < size.x + origin.x and
this.y >= origin.y and this.y < size.y + origin.y;
}
};

60
src/point.zig Normal file
View File

@@ -0,0 +1,60 @@
pub const Point = packed struct {
x: u16 = 0,
y: u16 = 0,
pub fn add(a: @This(), b: @This()) @This() {
return .{
.x = a.x + b.x,
.y = a.y + b.y,
};
}
pub fn max(a: @This(), b: @This()) @This() {
return .{
.x = @max(a.x, b.x),
.y = @max(a.y, b.y),
};
}
test "adding" {
const testing = @import("std").testing;
const a: @This() = .{
.x = 10,
.y = 20,
};
const b: @This() = .{
.x = 20,
.y = 10,
};
try testing.expectEqual(@This(){
.x = 30,
.y = 30,
}, a.add(b));
}
test "maximum" {
const testing = @import("std").testing;
const a: @This() = .{
.x = 10,
.y = 20,
};
const b: @This() = .{
.x = 20,
.y = 10,
};
try testing.expectEqual(@This(){
.x = 20,
.y = 20,
}, a.max(b));
}
};
test {
_ = Point;
}

View File

@@ -2,14 +2,13 @@ const std = @import("std");
const terminal = @import("terminal.zig");
const Cell = @import("cell.zig");
const Position = @import("size.zig").Position;
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
/// Double-buffered intermediate rendering pipeline
pub const Buffered = struct {
allocator: std.mem.Allocator,
created: bool,
size: Size,
size: Point,
screen: []Cell,
virtual_screen: []Cell,
@@ -30,9 +29,12 @@ pub const Buffered = struct {
}
}
pub fn resize(this: *@This(), size: Size) !void {
pub fn resize(this: *@This()) !void {
const size = terminal.getTerminalSize();
if (std.meta.eql(this.size, size)) return;
this.size = size;
const n = @as(usize, size.cols) * @as(usize, size.rows);
const n = @as(usize, this.size.x) * @as(usize, this.size.y);
if (!this.created) {
this.screen = this.allocator.alloc(Cell, n) catch @panic("render.zig: Out of memory.");
@@ -60,23 +62,21 @@ pub const Buffered = struct {
/// Render provided cells at size (anchor and dimension) into the *virtual screen*.
pub fn render(this: *@This(), comptime T: type, container: *T) !void {
const size: Size = container.size;
const cells: []const Cell = try container.contents();
const size: Point = container.size;
const origin: Point = container.origin;
const cells: []const Cell = try container.content();
if (cells.len == 0) return;
var idx: usize = 0;
var vs = this.virtual_screen;
const anchor: usize = (@as(usize, size.anchor.row) * @as(usize, this.size.cols)) + @as(usize, size.anchor.col);
const anchor: usize = (@as(usize, origin.y) * @as(usize, this.size.x)) + @as(usize, origin.x);
blk: for (0..size.rows) |row| {
for (0..size.cols) |col| {
const cell = cells[idx];
blk: for (0..size.y) |row| {
for (0..size.x) |col| {
vs[anchor + (row * this.size.x) + col] = cells[idx];
idx += 1;
vs[anchor + (row * this.size.cols) + col].style = cell.style;
vs[anchor + (row * this.size.cols) + col].cp = cell.cp;
if (cells.len == idx) break :blk;
}
}
@@ -88,19 +88,19 @@ pub const Buffered = struct {
/// Write *virtual screen* to alternate screen (should be called once and last during each render loop iteration in the main loop).
pub fn flush(this: *@This()) !void {
// TODO: measure timings of rendered frames?
// TODO measure timings of rendered frames?
const writer = terminal.writer();
const s = this.screen;
const vs = this.virtual_screen;
for (0..this.size.rows) |row| {
for (0..this.size.cols) |col| {
const idx = (row * this.size.cols) + col;
for (0..this.size.y) |row| {
for (0..this.size.x) |col| {
const idx = (row * this.size.x) + col;
const cs = s[idx];
const cvs = vs[idx];
if (cs.eql(cvs)) continue;
// render differences found in virtual screen
try terminal.setCursorPosition(.{ .row = @truncate(row + 1), .col = @truncate(col + 1) });
try terminal.setCursorPosition(.{ .y = @truncate(row + 1), .x = @truncate(col + 1) });
try cvs.value(writer);
// update screen to be the virtual screen for the next frame
s[idx] = vs[idx];

View File

@@ -1,17 +0,0 @@
pub const Size = packed struct {
anchor: Position = .{},
cols: u16 = 0,
rows: u16 = 0,
pub fn merge(this: @This(), other: @This()) Size {
return .{
.cols = this.cols + other.cols,
.rows = this.rows + other.rows,
};
}
};
pub const Position = packed struct {
col: u16 = 0,
row: u16 = 0,
};

View File

@@ -56,7 +56,7 @@ pub fn value(this: Style, writer: anytype, cp: u21) !void {
try std.fmt.format(writer, ";", .{});
try this.bg.write(writer, .bg);
// underline
// FIX: assert that if the underline property is set that the ul style and the attribute for underlining is available
// FIX assert that if the underline property is set that the ul style and the attribute for underlining is available
try std.fmt.format(writer, ";", .{});
try this.ul.write(writer, .ul);
// append styles (aka attributes like bold, italic, strikethrough, etc.)
@@ -67,6 +67,6 @@ pub fn value(this: Style, writer: anytype, cp: u21) !void {
try std.fmt.format(writer, "\x1b[0m", .{});
}
// TODO: implement helper functions for terminal capabilities:
// TODO implement helper functions for terminal capabilities:
// - links / url display (osc 8)
// - show / hide cursor?

View File

@@ -4,8 +4,8 @@ const ctlseqs = @import("ctlseqs.zig");
const input = @import("input.zig");
const Key = input.Key;
const Position = @import("size.zig").Position;
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
const Size = @import("point.zig").Point;
const Cell = @import("cell.zig");
const log = std.log.scoped(.terminal);
@@ -23,7 +23,7 @@ pub const ReportMode = enum {
pub fn getTerminalSize() Size {
var ws: std.posix.winsize = undefined;
_ = std.posix.system.ioctl(std.posix.STDIN_FILENO, std.posix.T.IOCGWINSZ, @intFromPtr(&ws));
return .{ .cols = ws.col, .rows = ws.row };
return .{ .x = ws.col, .y = ws.row };
}
pub fn saveScreen() !void {
@@ -89,9 +89,9 @@ pub fn writer() Writer {
return .{ .context = .{} };
}
pub fn setCursorPosition(pos: Position) !void {
pub fn setCursorPosition(pos: Point) !void {
var buf: [64]u8 = undefined;
const value = try std.fmt.bufPrint(&buf, "\x1b[{d};{d}H", .{ pos.row, pos.col });
const value = try std.fmt.bufPrint(&buf, "\x1b[{d};{d}H", .{ pos.y, pos.x });
_ = try std.posix.write(std.posix.STDIN_FILENO, value);
}
@@ -137,8 +137,8 @@ pub fn getCursorPosition() !Size.Position {
}
return .{
.row = try std.fmt.parseInt(u16, row[0..ridx], 10) - 1,
.col = try std.fmt.parseInt(u16, col[0..cidx], 10) - 1,
.x = try std.fmt.parseInt(u16, col[0..cidx], 10) - 1,
.y = try std.fmt.parseInt(u16, row[0..ridx], 10) - 1,
};
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -5,21 +5,20 @@ const Container = @import("container.zig").Container;
const Cell = @import("cell.zig");
const DisplayWidth = @import("DisplayWidth");
const Position = @import("size.zig").Position;
const Size = @import("size.zig").Size;
const Point = @import("point.zig").Point;
// TODO: how would I describe the expected screens?
// TODO how would I describe the expected screens?
// - including styling?
// - compare generated strings instead? -> how would this be generated for the user?
/// Single-buffer test rendering pipeline for testing purposes.
pub const Renderer = struct {
allocator: std.mem.Allocator,
size: Size,
size: Point,
screen: []Cell,
pub fn init(allocator: std.mem.Allocator, size: Size) @This() {
const screen = allocator.alloc(Cell, @as(usize, size.cols) * @as(usize, size.rows)) catch @panic("testing.zig: Out of memory.");
pub fn init(allocator: std.mem.Allocator, size: Point) @This() {
const screen = allocator.alloc(Cell, @as(usize, size.x) * @as(usize, size.y)) catch @panic("testing.zig: Out of memory.");
@memset(screen, .{});
return .{
@@ -33,9 +32,9 @@ pub const Renderer = struct {
this.allocator.free(this.screen);
}
pub fn resize(this: *@This(), size: Size) !void {
pub fn resize(this: *@This(), size: Point) !void {
this.size = size;
const n = @as(usize, size.cols) * @as(usize, size.rows);
const n = @as(usize, size.x) * @as(usize, size.y);
this.allocator.free(this.screen);
this.screen = this.allocator.alloc(Cell, n) catch @panic("testing.zig: Out of memory.");
@@ -47,21 +46,22 @@ pub const Renderer = struct {
}
pub fn render(this: *@This(), comptime T: type, container: *const T) !void {
const size: Size = container.size;
const cells: []const Cell = try container.contents();
const size: Point = container.size;
const origin: Point = container.origin;
const cells: []const Cell = try container.content();
if (cells.len == 0) return;
var idx: usize = 0;
const anchor = (@as(usize, size.anchor.row) * @as(usize, this.size.cols)) + @as(usize, size.anchor.col);
const anchor = (@as(usize, origin.y) * @as(usize, this.size.x)) + @as(usize, origin.x);
blk: for (0..size.rows) |row| {
for (0..size.cols) |col| {
blk: for (0..size.y) |row| {
for (0..size.x) |col| {
const cell = cells[idx];
idx += 1;
this.screen[anchor + (row * this.size.cols) + col].style = cell.style;
this.screen[anchor + (row * this.size.cols) + col].cp = cell.cp;
this.screen[anchor + (row * this.size.x) + col].style = cell.style;
this.screen[anchor + (row * this.size.x) + col].cp = cell.cp;
if (cells.len == idx) break :blk;
}
@@ -92,7 +92,7 @@ pub const Renderer = struct {
/// var renderer: testing.Renderer = .init(allocator, size);
/// defer renderer.deinit();
///
/// try container.handle(.{ .resize = size });
/// try container.handle(.{ .size = size });
/// try renderer.render(Container(event.SystemEvent), &container);
/// try renderer.save(file.writer());
/// ```
@@ -115,34 +115,36 @@ pub const Renderer = struct {
/// .cols = 30,
/// }, &container, @import("test/container/border.all.zon"));
/// ```
pub fn expectContainerScreen(size: Size, container: *Container(event.SystemEvent), expected: []const Cell) !void {
pub fn expectContainerScreen(size: Point, container: *Container(event.SystemEvent), expected: []const Cell) !void {
const allocator = std.testing.allocator;
var renderer: Renderer = .init(allocator, size);
defer renderer.deinit();
try container.handle(.{ .resize = size });
try renderer.resize(size);
container.resize(size);
container.reposition(.{});
try renderer.render(Container(event.SystemEvent), container);
try expectEqualCells(renderer.size, expected, renderer.screen);
try expectEqualCells(.{}, renderer.size, expected, renderer.screen);
}
/// This function is intended to be used only in tests. Test if the two
/// provided cell arrays are identical. Usually the `Cell` slices are
/// the contents of a given screen from the `zterm.testing.Renderer`. See
/// `zterm.testing.expectContainerScreen` for an example usage.
pub fn expectEqualCells(size: Size, expected: []const Cell, actual: []const Cell) !void {
pub fn expectEqualCells(origin: Point, size: Point, expected: []const Cell, actual: []const Cell) !void {
const allocator = std.testing.allocator;
try std.testing.expectEqual(expected.len, actual.len);
try std.testing.expectEqual(expected.len, @as(usize, size.rows) * @as(usize, size.cols));
try std.testing.expectEqual(expected.len, @as(usize, size.y) * @as(usize, size.x));
var expected_cps = try std.ArrayList(Cell).initCapacity(allocator, size.cols -| size.anchor.col);
var expected_cps = try std.ArrayList(Cell).initCapacity(allocator, size.x);
defer expected_cps.deinit();
var actual_cps = try std.ArrayList(Cell).initCapacity(allocator, size.cols -| size.anchor.col);
var actual_cps = try std.ArrayList(Cell).initCapacity(allocator, size.x);
defer actual_cps.deinit();
var output = try std.ArrayList(u8).initCapacity(allocator, expected_cps.capacity * actual_cps.capacity + 5 * size.rows);
var output = try std.ArrayList(u8).initCapacity(allocator, expected_cps.capacity * actual_cps.capacity + 5 * size.y);
defer output.deinit();
var buffer = std.io.bufferedWriter(output.writer());
@@ -155,23 +157,22 @@ pub fn expectEqualCells(size: Size, expected: []const Cell, actual: []const Cell
defer dwd.deinit();
const dw: DisplayWidth = .{ .data = &dwd };
const expected_centered = try dw.center(allocator, "Expected Screen", size.cols, " ");
const expected_centered = try dw.center(allocator, "Expected Screen", size.x, " ");
defer allocator.free(expected_centered);
const actual_centered = try dw.center(allocator, "Actual Screen", size.cols, " ");
const actual_centered = try dw.center(allocator, "Actual Screen", size.x, " ");
defer allocator.free(actual_centered);
try writer.print("Screens are not equivalent.\n{s} ┆ {s}\n", .{ expected_centered, actual_centered });
const anchor = (size.anchor.row * size.cols) + size.anchor.col;
for (size.anchor.row..size.rows) |row| {
for (origin.y..size.y) |row| {
defer {
expected_cps.clearRetainingCapacity();
actual_cps.clearRetainingCapacity();
}
for (size.anchor.col..size.cols) |col| {
const expected_cell = expected[anchor + (row * size.cols) + col];
const actual_cell = actual[anchor + (row * size.cols) + col];
for (origin.x..size.x) |col| {
const expected_cell = expected[(row * size.x) + col];
const actual_cell = actual[(row * size.x) + col];
if (!expected_cell.eql(actual_cell)) differ = true;

View File

@@ -1,13 +1,14 @@
// private imports
const container = @import("container.zig");
const color = @import("color.zig");
const size = @import("size.zig");
const size = @import("point.zig");
// public exports
pub const input = @import("input.zig");
pub const testing = @import("testing.zig");
pub const App = @import("app.zig").App;
pub const Error = @import("error.zig").Error;
// App also exports further types once initialized with the user events at compile time:
// `App.Container`
// `App.Element`
@@ -23,17 +24,17 @@ pub const Cell = @import("cell.zig");
pub const Color = color.Color;
pub const Key = input.Key;
pub const Mouse = input.Mouse;
pub const Position = size.Position;
pub const Size = size.Size;
pub const Point = @import("point.zig").Point;
pub const Style = @import("style.zig");
test {
_ = @import("terminal.zig");
_ = @import("container.zig");
_ = @import("queue.zig");
_ = @import("error.zig");
_ = @import("point.zig");
_ = color;
_ = size;
_ = Cell;
_ = Key;