197 Commits

Author SHA1 Message Date
6781c43fcc add(renderer/direct): write newline function to align view if necessary
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m8s
2026-01-27 15:33:35 +01:00
eb36c7c410 fix: correctly read inputs from *stdin* when not using *raw mode*
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m6s
2026-01-23 12:44:48 +01:00
4441f1b933 feat(app): event line provides entire line contents as a single event; add(event): .cancel event
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m5s
Introduce `.cancel` event that is fired when the user sends EOF
in *non raw mode* renderings. The event `.line` now sends the
entire line (even if larger than the internal buffer) but requires
now an `Allocator`.
2026-01-22 08:56:12 +01:00
39fb8af174 fix(app): do not reset remaining bytes after reading
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m15s
2026-01-22 07:15:46 +01:00
bfbe75f8d3 feat(inline): rendering without alternate screen
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (pull_request) Successful in 1m10s
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 55s
Fix issue with growth resize for containers with corresponding
borders, padding and gaps.
2026-01-20 23:09:16 +01:00
89517b2546 fix: add newly introduced parameter for App.start function to all corresponding usages 2026-01-20 15:16:10 +01:00
a71d808250 add: .line core event for line contents in non *raw mode* instead of .key core events
The end of the `.line` event received contents is highlighted by a trailing newline
(which cannot occur before, as that triggers the line event itself).

Add signal handler for SIGCONT which forces a `.resize` event that should re-draw the
contents after continuing a suspended application (i.e. ctrl+z followed by `fg`).
2026-01-20 15:11:19 +01:00
97a240c54d mod: example shows how dynamic sizing is achived that can be independent form the reported terminal size
Setting the cursor with the `Direct` handler will cause the rendering
to halt at that point and leave the cursor at point.

Due to not enabling *raw mode* with the newly introduced `App.start`
configuration options corresponding inputs are only visible to `zterm`
once the input has been completed with a newline. With this it is not
necessary for the renderer to know nothing more than the width of the
terminal (which is implied through the `Container` sizes). Making it
very trivial to implement.
2026-01-20 13:57:55 +01:00
c29c60bd89 WIP make example interactive
Handle inputs as per usual (which however is a bit weak, is it goes through
key by key and not the entire line), batch all events such that all events
are handled before the next frame is rendered. For this the `App.start`
function needs to become configurable, such that it changes the termios as
configured (hence it is currently all commented out for testing).
2026-01-20 11:54:28 +01:00
4a3bec3edc add: Direct Renderer implementation rendering the fixed size of the root Container
A corresponding example has been added, which is very minimalistic as of now,
but will add further functionality to test the corresponding workflow that is
usual in `zterm` such that it in the best case only a swap in the renderer to
switch from alternate mode drawing to direct drawing.
2026-01-20 11:28:37 +01:00
836d7669e5 feat: introduce growth options .horizontal_only and .vertical_only
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m5s
Growing containers only in one specific direction while fixing the
other dimension (which is then required to be provided - just like
before).
2026-01-18 13:36:03 +01:00
1621715ad8 lint: correct typo
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m7s
2026-01-17 12:29:42 +01:00
4874252e8c mod: adapt implementation to zig version 0.15.2
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 54s
2026-01-17 12:05:20 +01:00
e1e8907848 doc: remove hint as builds now use latest zig version 2026-01-17 12:04:52 +01:00
1cb7fca701 mod(ci): change target zig version to *latest* 2026-01-17 12:04:19 +01:00
19d1602d3b ref: omit capture instead of dropping
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 49s
2026-01-12 23:28:30 +01:00
88c7eea356 feat(unicode): accept unicode characters through the app's input handler to be handled correctly; key introduce isUnicode method
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m21s
With the `isUnicode` method the read unicode characters from the user
can be checked against displayable text and rendered on the screen accordingly.
2026-01-12 22:47:20 +01:00
b1a0d60ae3 mod: bump zig master version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m9s
2026-01-06 22:58:10 +01:00
c49c2a5c6d mod(app): export TextField from App to be used in other Element implementations similar to App.Input
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m1s
2025-12-27 19:56:44 +01:00
8b5d3757fc mod(element/Input): split into TextField without associated event to automatically trigger
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m9s
2025-12-27 17:06:07 +01:00
06ab32bdde mod(container): Size property handling for .fixed, .horizontal and .vertical check with assertions required values
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m0s
2025-12-17 22:58:58 +01:00
8e3b43fa61 mod(container): .horizontal and .vertical size.grow respect minSize value if no size.dim is used
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m0s
2025-12-17 22:48:02 +01:00
6b2797cd8c mod(container): .fixed sizing behavior with minSize Container / Element function
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m1s
2025-12-17 22:04:06 +01:00
e972a2ea0f mod(container): integrate minSize call when fit_resize is calculated
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 57s
2025-11-28 15:31:45 +01:00
67bfd90a2c WIP(container): fit_size call minSize for determining the minimal required size of a given Container
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 57s
2025-11-28 15:25:10 +01:00
40fa080af6 WIP(container): use another approach
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 57s
2025-11-28 15:08:58 +01:00
d92f562a57 WIP(container): propagate individual child sizes correctly
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 57s
2025-11-28 15:03:50 +01:00
f7025a0fc2 fix(container): minSize should not add children's sizes, but take max instead
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 57s
2025-11-28 14:34:32 +01:00
41229c13d3 mod(container): provide minSize function for Element implementation to refer for nested structures
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m6s
2025-11-28 14:27:41 +01:00
855594a8c8 mod(element): introduce deinit interface for deinitializing Elements automatically with the Container
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m34s
2025-11-27 21:13:03 +01:00
9488d0b64d feat(terminal/cursor): add support for cursor shape configuration
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m5s
2025-11-20 18:46:58 +01:00
424740d350 feat(terminal/osc12): define cursor color through style of cell that describes the cursor position
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m33s
The `.default` color will reset the cursor color to the terminal's default color
2025-11-19 18:42:13 +01:00
28c733352e feat(event): introduce .bell system event
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 16m37s
2025-11-17 18:30:31 +01:00
3b5507ec1e fix(lint): correct typo
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m4s
2025-11-10 17:18:36 +01:00
38d31fae72 feat(element): parameter *const App.Model
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 55s
The renderer will provide `resize`, `reposition` and `minSize` (for
the `Scrollable` `Element`) with a read-only pointer to the model of
the application (similar to how it is already done for `handle` and
`content`). Every interface function now has the same data that it can
each use for implementing its corresponding task based on local and
shared variables through the element instance and model pointer.
2025-11-10 17:09:29 +01:00
79a0d17a66 feat(io): introduce std.Io parameter for App.init
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m22s
The provided `std.Io` is used for running the input reading and the
rendering asynch. The user can provide their desired `std.Io`
implementation as they wish to use. The examples use `std.Io.Threaded`
as a simple threaded solution.
2025-11-10 16:44:02 +01:00
accbb4c97d mod: bump action dependencies
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 56s
2025-11-05 22:45:56 +01:00
ad32e46bc9 feat(element/scrollable): mouse support for scrollbar interaction
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 55s
Fix an issue with the scrollbar contents to work proper with statically
defined `Container` sizes through its `Properties` sizing option.
2025-11-05 22:08:35 +01:00
8ebab702ac fix(element/scrollable): reduce the number of minSize calls and correctly resize scrollable Container
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m26s
2025-11-05 18:33:16 +01:00
e53bb7880b mod: cleanup TODO and outdated comments 2025-11-05 18:32:49 +01:00
a83e86f8d9 feat(element/scrollable): background configuration
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m30s
2025-11-02 21:00:17 +01:00
4567963ff2 mod(example/text): improve event loop; add stick table heading for used emphasis
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 59s
This should be the way it should be done all the time, such that you
are not rendering for every input, but instead handle all `App.Event`s
that happened between the last render and the current. This shares
similarities with the continuous event loops, which also batches
the events only with the exception that it instead blocks (see
`App.Queue.poll`).
2025-11-02 16:10:11 +01:00
d4cc520826 fix(element/scrollable): display and user interaction
Fix initial render to show scrollbar immediately if required. Show and
hide scrollbar correctly when content size or terminal size changes. Add
keybindings for scrolling similar to pager keybindings.
2025-11-02 16:05:53 +01:00
b3dc8096d7 mod(event): do not care about enum declarations
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 56s
The union type can not be constructed with declarations anyway:
`error: reified unions must have no decls`; meaning there is no point in
even trying to do so.
2025-11-01 21:44:53 +01:00
7cd1fb139f mod(element/scrollable): ensure minSize returns correct dimensions
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 56s
Enforce that `minSize` returns a `Point` with corresponding minimal
dimensions with respect to the provided available size. This means that
an `Element` implementation that provides a `minSize` function may even
return a too small dimension, which would automatically be resized to be
at least as big as the provided size.
2025-11-01 14:37:14 +01:00
f70ea05244 mod(element/scrollable): introduce minSize function for Element
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 3m24s
The minimal required size can the queried from the containing `Element`
of the `Container` that is provided to the `Scrollable` to dynamically
adjust its size.

Currently abritrary nesting is not supported / tested.
2025-11-01 13:55:16 +01:00
c645c2efee fix: changes from newest zig version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m3s
2025-11-01 00:03:04 +01:00
89aeac1e96 doc: correct alert blocks
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m0s
2025-10-26 21:46:00 +01:00
feae9fa1a4 feat(model): implement Elm architecture
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m2s
Now the `App` contains a state which is a user-defined `struct` which
is passed to the `handle` and `contents` callbacks for `Container`'s and
`Element`'s. Built-in `Element`'s shall not access the `App.Model` and
should therefore never cause any side-effects.

User-defined events shall be used to act as *messages* to cause
potential side-effects for the model. This is the reason why only
the `handle` callback has a non-const pointer to the `App.Model`. The
`contents` callback can only access the `App.Model` read-only to use for
generating the *view* (in context of the elm architecture).
2025-10-26 15:58:07 +01:00
8f90f57f44 fix(terminal): correctly restore termios and screen's during panic_handler
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m1s
2025-10-19 11:44:17 +02:00
fee3c796d9 doc(terminal): remove resolved issue
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m0s
2025-10-18 23:31:49 +02:00
547f553404 fix(terminal): restore screen correctly with alt screen
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m3s
2025-10-18 23:30:15 +02:00
1f6bbcc45e mod(examples/progress): show multiple different configuration options
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 59s
2025-10-01 11:14:22 +02:00
832fc45c3e chor: use new Writer interface for terminal's Writer; fix test cases
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 3m38s
2025-10-01 10:59:29 +02:00
aa17e13b99 lint: correct typo
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 58s
2025-09-29 23:11:28 +02:00
cba07b119c chor: upgrade to latest zig; remove zg dependency
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 55s
2025-09-29 23:09:42 +02:00
f256a79da0 chor: bumb zig version to 0.16.0-dev
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m41s
2025-08-27 12:17:20 +02:00
c50b10f32d fix: zig update build errors
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m35s
2025-08-06 16:14:22 +02:00
4f6cabf898 chor: update zig version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m3s
2025-08-04 21:09:56 +02:00
853f4d9769 mod(event): documentation of unsupported creation of declarations during comptime
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 56s
The functionality remains in the code, but will cause an compilation
error when the user provided tagged union for the application events
has declarations. This way it is at least explicit that no declarations
are supported (even if this is actually a nice to have).

For details see this [issue](https://github.com/ziglang/zig/issues/6709).
2025-07-17 23:15:45 +02:00
edbca39c38 mod(event): merge the declarations of the tagged unions alongside the fields
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 55s
2025-07-17 22:27:02 +02:00
0de50e7016 feat(element/selection): Element implementation for selecting an enum variant
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m35s
2025-07-17 21:00:00 +02:00
088e1a9246 add(element/radio-button): RadioButton Element implementation
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 2m6s
This can be used to visualize the values of `bool`'s, which is relevant
when creating form's based on `struct`'s automatically.
2025-07-13 21:02:28 +02:00
df78c7d6eb mod: bump zg dependency version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m19s
2025-07-11 22:38:47 +02:00
66b3a77805 feat(container): negative layout padding
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Has been cancelled
Negative paddings use the current size to calculate the padding from
the opposite orientation. For a given dimension (horizontal or vertical)
if the size is `30` a padding of `5` would be equivalent to a padding
of `-25`. This enables to describe the size of the container using
the padding property of the `Layout` and gives users more freedom to
describe different layouts.
2025-07-11 22:33:32 +02:00
b401b5ece8 lint(container): style
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m41s
2025-07-07 23:08:06 +02:00
9f33c902ee mod(container): cleanup and highlight points for improvement
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m42s
2025-07-06 00:42:00 +02:00
9f29ac6a77 feat(element/progress): Progress bar implementation as an Element
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 2m42s
2025-07-05 18:29:49 +02:00
f775a6ab2d formatting
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 13s
2025-06-30 22:53:05 +02:00
a39cee7ccb feat(element/button): add builtin Element implementation for buttons 2025-06-30 22:52:27 +02:00
7875db0aea feat(element/input): make accept event agnostic to u8 and u21 slices
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 50s
There are now comptime checks in place an the corresponding triggered
event will be automatically converted to the correct type to support
simple ascii strings (`[]u8`) or utf-8 strings (`[]u21`).
2025-06-30 22:03:59 +02:00
7595e3b5bb feat(element/input): text input element implementation
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 14s
Moved implementation from example/input as a standalone `Element`
implementation, which is directly used by the example instead.

The provided argument is the `App.Event`'s event that should be
triggered on acceptance for the contents of the Input `Element`.
Currently only `[]u21` strings are supported, but in the future also
`[]u8` strings shall be supported and automatically converted when
pushed as an `App.Event` into the app's queue.
2025-06-29 11:19:09 +02:00
2ba0ed85fb fix(app): remove exported Exec Element - it does not exist in this branch 2025-06-29 10:34:53 +02:00
439520d4fe mod(example/input): ellipse rendering with scrolling for text field contents
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 17s
2025-06-28 22:09:36 +02:00
ded1f2c17e mod(example/input): reorder input handling cases; add alt-b/f binding implementations 2025-06-28 22:08:19 +02:00
92ae8c9681 feat(example/input): readline shortcuts; better navigation;
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 58s
This will be the basis for a Textfield `Element` implementation to make
it easier to add user inputs into the container structures.
2025-06-28 13:04:00 +02:00
743cdca174 mod: bump zg dependency version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 26s
As the dependency is still using version 0.14.0, it still causes an
error during testing. Corresponding examples are still working as
expected.
2025-06-24 20:48:32 +02:00
7d8e902ce2 chor: bump zig version and fix corresponding errors 2025-06-24 20:47:47 +02:00
ed0010c8af lint: correct reported typos (including a rename)
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 26s
2025-06-24 20:35:28 +02:00
a8e138deb7 action: bump zig installation version
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 15s
2025-06-24 20:27:07 +02:00
d0453d08b8 fix: render cursor correctly in case the same character remains the cursor position
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 47s
2025-06-11 20:32:35 +02:00
825fb63bc8 ref: rename gpa usages to the aliased DebugAllocator 2025-06-11 20:31:41 +02:00
76f708d9d7 add(continous): example which provides a fixed render schedule
The other examples did rendering based on events, which this renderer
does not. This makes these applications potentially not that efficient,
but allows for consistent frame times that make animations, etc.
possible. This example serves to show that you can use `zterm` for both
types of render scheduling and even change between them without much
efford.
2025-05-30 23:02:56 +02:00
0d2644f476 mod(input): handle remaining key codes remove unused ones 2025-05-30 23:01:48 +02:00
9a818117d7 feat(panic): panic handler to recover termios when crashing 2025-05-30 23:00:45 +02:00
5ba5b2b372 feat(element/alignment): alignment Element implementation
You can now align a `Container` using the Alignment `Element` similar to
how you make a `Container` scrollable. For usage details please see the
example and the corresponding tests.
2025-05-28 14:42:02 +02:00
3cb0d11e71 add: necessary assert statement; rem: unnecessary render resize in testing 2025-05-28 14:40:25 +02:00
4cc749facc feat(app): read input options correctly 2025-05-28 14:39:27 +02:00
c6d8eec287 feat(debug): render debug support 2025-05-26 15:43:47 +02:00
2572b57697 refactor: remove unnecessary comptime keyword 2025-05-26 15:15:30 +02:00
80a36a9947 refactor: zigify imports and usages 2025-05-26 14:23:18 +02:00
4cde0640c8 fix(element/scrollable): adjust anchor for scrollable element during resize 2025-05-22 23:39:05 +02:00
e9a9c2b680 feat(app): signal WINCH for .resize system event
This allows the application to automatically re-draw and resize if the
application receives the signal by the terminal emulator.
2025-05-21 22:49:08 +02:00
ba25e6056c feat(element/scrollable): scrollbar rendering
Configuration to enable scrollbar rendering for scrollable `Element`s.
Currently only the fg `Color` of the scrollbar can be configured while
the background uses the same fg `Color` but adds the emphasis `.dim` to
make it obvious what the is the actual scrollbar. In the future it might
be necessary to provide the user with more options to configure the
representation of the scrollbar.

Tests have been added to test the scrollbar rendering and placement
accordingly.
2025-05-21 18:20:52 +02:00
aa4adf20f9 refactor: zigify imports and correct minor mistakes 2025-05-20 18:23:44 +02:00
50adf32f14 add(style): cursor style to indicate a cursor position
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 25s
2025-04-20 20:54:30 +02:00
a4293ff243 add(event): mouse event has relative position for receiving elements
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Has been cancelled
2025-04-20 20:53:46 +02:00
50450f3bbc fix(container): growth resize for size all size options and starting sizes (i.e. the smallest being a non grow-able one)
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m14s
2025-04-07 20:55:21 +02:00
bce134f052 rem: unnecessary signal handler
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 2m1s
No event-based re-sizing, instead each re-render resizes by default.
2025-04-01 21:53:52 +02:00
962a384ecf add(Scrollable): init function with corresponding usages
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 42s
2025-03-29 21:21:23 +01:00
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
9d5a661b4e test(container): render Cell slices test against .zon input
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m0s
2025-02-25 18:41:04 +01:00
4234c9ad0c rem(element): template Element moved into wiki documentation
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 45s
2025-02-25 16:55:11 +01:00
a588e2ef21 add(test): input testing of Key.isAscii
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m42s
2025-02-25 16:52:17 +01:00
8519d204f3 fix(lint): correct spelling error
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m1s
2025-02-24 17:20:25 +01:00
33262c9638 add(testing): new namespace containing testing capabilities for zterm
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s
The namespace shall also be used for testing the rendering of
`Container`s and `Element`s (including the `Scrollable` element).

The testing renderer currently is a striped down version of the double
buffered render without the secondary buffer and the flushing to stdout.
The internal `Cell` slice (the *screen*) is used for equality checks.

The testing namespace shall provide a way to describe the expected
`Cell` slices that should be validated against.
2025-02-24 17:14:57 +01:00
5c5c59cbfc fix(style): render only necessary bytes and change default fg color to .default
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 45s
2025-02-24 17:11:22 +01:00
c022d1d9e2 fix(lint): correct indentation and naming convention for constants
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 1m9s
2025-02-24 17:09:22 +01:00
12497e92f8 fix(lint): correct casing for constants
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 21s
2025-02-24 17:01:55 +01:00
d10f738c75 add(test): cell conversion to ansi enhanced strings
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 45s
2025-02-24 16:54:05 +01:00
140f27216a doc: move contents from README to wiki
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 6m49s
2025-02-22 11:00:38 +01:00
04ba88c68b doc: update README
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 42s
2025-02-21 23:17:01 +01:00
6ccab74c94 add(examples/demo): application to showcase a more complex application
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 53s
Further improvements for example applications; Demo example is now
default build target (when not providing example configuration).
2025-02-21 22:57:14 +01:00
c634e1affc doc: update roadmap 2025-02-21 22:29:19 +01:00
dab486a2c1 add(examples/errors): error notifaction handling
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m33s
2025-02-21 22:25:42 +01:00
9b0dd3c52f doc: correct link to wiki
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 43s
2025-02-21 19:17:28 +01:00
f45e722578 fix(linter): spelling error in README
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 57s
2025-02-21 19:15:19 +01:00
7b005ea4b1 add(examples/styles): text and color styling possiblities
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s
This also contains some minor refactoring to improve the readability
and understandability of the library (i.e. renaming of Style.Attributes
to Style.Emphasis).
2025-02-21 19:13:11 +01:00
c0c0590bb9 add(examples/styles): color palette to showcase all available colors to render (except for .default)
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 54s
2025-02-21 16:43:03 +01:00
16724f6a52 add(example/elements): distinct different scrollable containers
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-02-21 15:58:42 +01:00
44e92735cf ref(examples): avoid unnecessary casts
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 43s
2025-02-21 15:15:15 +01:00
8cc047c1fa fix(lint): spelling error in README
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 57s
2025-02-21 14:57:30 +01:00
8fbc958ca1 add(examples/elements): mouse clickable button
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s
2025-02-21 14:50:29 +01:00
b980703350 fix(container): border separator handling
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s
Due to the assigning back the increased value for the used gap in case
the separator was active, every .resize `Event` would add more to the
gap, leading to ever smaller sub-container's and different sizes after
resizes. This has been fixed to have consistent layouting done by the
`Container` and `Border`.
2025-02-21 12:25:47 +01:00
eb89f7f98b fix(renderer): reset color after each cell write
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 38s
2025-02-21 12:19:38 +01:00
cc847b7035 add(examples/layout): mixed content with different layout options 2025-02-21 12:19:16 +01:00
9dc1a4b95a add(examples/layout): vertical, horizontal and grid
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 39s
2025-02-21 11:31:18 +01:00
69c1600eb9 mod(build): adjust name of enum values to be easier to type in command line
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 54s
2025-02-20 23:54:53 +01:00
c4639bf4bb add(example): input with simple text field
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m41s
2025-02-20 23:48:57 +01:00
07e932741c doc: update roadmap and further goals
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 43s
2025-02-20 18:56:56 +01:00
e4ff240839 doc: update roadmap and contents for future documentation goals
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 44s
2025-02-20 11:49:30 +01:00
96375e3b72 mod(build): build configuration for examples
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 54s
2025-02-20 11:16:42 +01:00
9322785ca0 mod: update zig version
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 43s
2025-02-19 22:55:03 +01:00
cc831a5cdf fix(element/scrollable): render horizontal directed contents correctly
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-02-19 22:23:32 +01:00
86b3e7d4ed feat(scrollable): make Container scrollable through Element Scrollable
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m35s
2025-02-19 20:32:26 +01:00
f55d71a7cb mod(mouse): fix input.Mouse.in method
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
Pass through mouse events where they actually match the corresponding
`Container`. Adopt mouse event accordingly in `Scrollable` `Element`
trait when passing through the mouse event to the scrollable
`Container`.
2025-02-18 19:09:03 +01:00
f66a870223 ref(input): move mouse.zig and key.zig into public input.zig namespace
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m41s
2025-02-18 18:24:09 +01:00
e2f9408850 add(input): mouse support
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-02-17 23:36:27 +01:00
c2080ab40f ref(ctlseqs): use control sequence file; rename key names
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 46s
2025-02-17 23:08:47 +01:00
a9f48bfb6a ref(key): make Key struct packed and rename constants
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 2m5s
2025-02-17 21:06:15 +01:00
7891af6c6f add(element/scrollable): implement content provider
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 1m49s
However this is only working for the same size as the parent container
(i.e. same `Size`). The `.resize` event for the `Container` of the
scrollable element needs to be the necessary and/or required size for
the contents (regardless of the screen viewport).
2025-02-17 19:58:25 +01:00
7b690d387b fix(lint): correct spelling errors
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (pull_request) Successful in 1m9s
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 42s
2025-02-16 16:01:04 +01:00
5c929479b2 add(main): main executable with zig build run support
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (pull_request) Failing after 5m10s
The main executable contains a simple `Element` implementation example
showing how interaction through and outside of the event loop can be
implemented to impact the rendered contents.
2025-02-16 15:35:50 +01:00
d8a9e72b67 add(border): seperator line options with corresponding code points 2025-02-16 02:04:53 +01:00
d951906b2b rem: Scroll from Propierties of Container
Updated the corresponding documentation and ideas for how to realize
scrollable contents.
2025-02-15 18:50:36 +01:00
01eb14f1bd doc: update Roadmap section of README 2025-02-15 16:03:06 +01:00
1041b0a955 mod: update zg dependency
`zg` now supports zig 0.14 dev which this library already uses.
2025-02-15 16:00:55 +01:00
4781e9ce39 add(element): interface for injecting user behavior to containers
Some additional refactoring and documentation updates have also been
applied.
2025-02-15 15:56:30 +01:00
5c148e1aa5 fix(cotainer/border): seperator placement without border's and gap 2025-02-15 11:25:20 +01:00
a6aa6e5150 fix(container/border): correct location and rendering of separators between child elements 2025-02-15 11:10:37 +01:00
26d31a38de ref(container): use only one size for each container 2025-02-15 10:49:48 +01:00
01d121ef87 mod: update README and remove alignment options 2025-02-14 22:27:24 +01:00
abaea968a6 rem(container): sizing options
This enables the `Layout` struct to be packed (as well as the
`Properties` struct) which should further reduce the memory footprint.
2025-02-14 22:19:20 +01:00
73a7f740c9 ref(container): move size: Size member from Scroll to Container 2025-02-14 22:03:21 +01:00
c2a03e95c1 fix(container/layout): padding calculation for anchor corrections 2025-02-14 21:59:10 +01:00
8998afd9d6 mod(): 2025-02-14 21:49:30 +01:00
72 changed files with 7042 additions and 1201 deletions

View File

@@ -15,9 +15,15 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup zig installation
uses: mlugg/setup-zig@v1
uses: https://codeberg.org/mlugg/setup-zig@v2
with:
version: master
version: latest
- name: Lint check
run: zig fmt --check .
- name: Spell checking
uses: crate-ci/typos@v1.39.0
with:
config: ./.typos-config
- name: Run tests
run: zig build --release=fast
- name: Release build artifacts

View File

@@ -14,13 +14,13 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup zig installation
uses: mlugg/setup-zig@v1
uses: https://codeberg.org/mlugg/setup-zig@v2
with:
version: master
version: latest
- name: Lint check
run: zig fmt --check .
run: zig fmt --check --exclude src/test .
- name: Spell checking
uses: crate-ci/typos@v1.25.0
uses: crate-ci/typos@v1.39.0
with:
config: ./.typos-config
- name: Run tests

130
README.md
View File

@@ -1,9 +1,19 @@
# zterm Terminal User Interface Library
# zterm TUI Library
`zterm` is a terminal user interface library to implement terminal (fullscreen or inline) applications.
`zterm` is a terminal user interface library (*tui*) to implement terminal (fullscreen or inline) applications.
> [!NOTE]
> 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=demo run
```
> [!tip]
> Every example application can be quit using `ctrl+c`.
See the [wiki](https://gitea.yves-biener.de/yves-biener/zterm/wiki) for a showcase of the examples and the further details.
## Usage
@@ -13,117 +23,19 @@ To add or update `zterm` as a dependency in your project run the following comma
zig fetch --save git+https://gitea.yves-biener.de/yves-biener/zterm
```
Add the dependency to your module as follows in your _build.zig_:
Add the dependency to your module as follows in your *build.zig*:
```zig
const zterm: *Dependency = b.dependency("zterm", .{
.target = target,
.optimize = optimize,
});
// ...
exe.root_module.addImport("zterm", zterm.module("zterm"));
```
For an example you can take a look at [build.zig](build.zig) for an example.
### Documentation
---
## Design Goals
This project draws heavy inspiration from
[clay](https://github.com/nicbarker/clay) in the way the layout is declared by
the user. As terminal applications usually are rendered in intermediate mode,
the rendering is also part of the event loop. Such that every time an event
happens a render call will usually be done as well. However this is not strickly
necessary and can be separated to have a fixed rendering of every 16ms (i.e. for
60 fps), etc.
There is only one generic container which contains properties and elements (or
children) which can also be containers, such that each layout in the end is
a tree.
The library is designed to be very basic and not to provide any more complex
elements such as input fields, drop-down menu's, buttons, etc. Some of them are
either easy to implement yourself, specific for you needs or a too complex to
be provided by the library effectively. For these use-cases there may be other
libraries that build on top of this one to provide the complex elements as some
sort of pre-built elements for you to use in your application (or you create
them yourself).
There are only very few system events, that are used by the built-in containers
and properties accordingly. For you own widgets (i.e. a collection of elements)
you can extend the events to include your own events to communicate between
elements, effect the control flow and the corresponding generated layouts and
much more.
As this is a terminal based layout library it also provides a rendering pipeline
alongside the event loop implementation. Usually the event loop is waiting
blocking and will only cause a re-draw (**intermediate mode**) after each event.
Even though the each frame is regenerated from scratch each render loop, the
corresponding application is still pretty performant as the renderer uses a
double buffered intermediate mode implementation to only apply the changes from
each frame to the next to the terminal.
This library is also designed to work accordingly in ssh hosted environments,
such that an application created using this library can be accessed directly
via ssh. This provides security through the ssh protocol and can defer the
synchronization process, as users may access the same running instance. Which is
the primary use-case for myself to create this library in the first place.
---
## Roadmap
- [ ] Container rendering
- [ ] Layout
- [x] direction
- [x] vertical
- [x] horizontal
- [x] padding
- [x] gap
- [ ] alignment
- [ ] center
- [ ] left
- [ ] right
- [ ] sizing
- [ ] width
- [ ] height
- [ ] options
- [ ] fit
- [ ] grow
- [x] fixed
- [x] percent
- [ ] Border
- [x] sides
- [x] corners
- [ ] separators
- [x] Rectangle
- [ ] Scroll
- [ ] vertical
- [ ] horizontal
- [ ] scroll bar(s)
Decorations should respect the layout and the viewport accordingly. This means
that scrollbars are always visible (except there is no need to have a scrollbar)
irrelevant depending on the size of the content. The rectangle apply to all
cells of the content (and may be overwritten by child elements contents).
The border of an element should be around independent of the scrolling of the
contents, just like padding.
- *fit*: adjust virtual space of container by the size of its children (i.e. a
container needs to be able to get the necessary size of its children)
- *grow*: use as much space as available (what exactly would be the difference
between this option and *fit*?)
- *fixed*: use exactly as much cells (in the specified direction)
- *center*: elements should have their anchor be placed accordingly to their
size and the viewport size.
- *left*: the anchor remains at zero (relative to the location of the
container on the screen) -> similar to the current implementation!
- *right*: the anchor is fixed to the right side (i.e. size of the contents -
size of the viewport)
### Input
How is the user input handled in the containers? Should there be active
containers? Some input may happen for a specific container (i.e. when using
mouse input). How would I handle scrolling for outer and inner elements of
a container?
A wiki should be created containing a bright overview of the structure and usage
of the library. For details it should refer to the examples. The documentation
should be minimal in terms of updateability in case the library changes. Maybe
some documentation could be derived from the code documentation (there is a tool
for this if I recall correctly).

112
build.zig
View File

@@ -1,41 +1,111 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const zg = b.dependency("zg", .{
.target = target,
.optimize = optimize,
});
const Examples = enum {
all,
demo,
continuous,
// elements:
alignment,
button,
input,
progress,
radio_button,
scrollable,
selection,
// layouts:
vertical,
horizontal,
grid,
mixed,
// styles:
text,
palette,
// error handling
errors,
// non alternate screen applications
direct,
};
const example = b.option(Examples, "example", "Example to build and/or run. (default: all)") orelse .all;
const debug_rendering = b.option(bool, "debug", "Enable debug rendering. Highlight origin's, size's, padding's, gap's, etc. (default: false)") orelse false;
// NOTE do not support debug rendering in release builds
if (debug_rendering == true and optimize != .Debug) @panic("Cannot enable debug rendering in non-debug builds.");
const options = b.addOptions();
options.addOption(bool, "debug", debug_rendering);
const options_module = options.createModule();
// library
const lib = b.addModule("zterm", .{
.root_source_file = b.path("src/zterm.zig"),
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "build_options", .module = options_module },
},
});
lib.addImport("code_point", zg.module("code_point"));
const container = b.addExecutable(.{
.name = "container",
.root_source_file = b.path("examples/container.zig"),
.target = target,
.optimize = optimize,
});
container.root_module.addImport("zterm", lib);
b.installArtifact(container);
//--- Examples ---
const examples = std.meta.fields(Examples);
inline for (examples) |e| {
if (@as(Examples, @enumFromInt(e.value)) == .all) continue; // skip `.all` entry
const demo = b.addExecutable(.{
.name = e.name,
.root_module = b.createModule(.{
.root_source_file = b.path(switch (@as(Examples, @enumFromInt(e.value))) {
.demo => "examples/demo.zig",
.continuous => "examples/continuous.zig",
// elements:
.alignment => "examples/elements/alignment.zig",
.button => "examples/elements/button.zig",
.input => "examples/elements/input.zig",
.progress => "examples/elements/progress.zig",
.radio_button => "examples/elements/radio-button.zig",
.scrollable => "examples/elements/scrollable.zig",
.selection => "examples/elements/selection.zig",
// layouts:
.vertical => "examples/layouts/vertical.zig",
.horizontal => "examples/layouts/horizontal.zig",
.grid => "examples/layouts/grid.zig",
.mixed => "examples/layouts/mixed.zig",
// styles:
.text => "examples/styles/text.zig",
.palette => "examples/styles/palette.zig",
// error handling
.errors => "examples/errors.zig",
// non-alternate screen
.direct => "examples/direct.zig",
.all => unreachable, // should never happen
}),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "zterm", .module = lib },
},
}),
});
// mapping of user selected example to compile step
if (@intFromEnum(example) == e.value or example == .all) b.installArtifact(demo);
}
// testing
// zig build test
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/zterm.zig"),
.target = target,
.optimize = optimize,
.root_module = b.createModule(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "build_options", .module = options_module },
},
}),
});
lib_unit_tests.root_module.addImport("code_point", zg.module("code_point"));
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);
}
const std = @import("std");

View File

@@ -6,34 +6,40 @@
//
// 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.3.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`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
.zg = .{
.url = "git+https://codeberg.org/atman/zg#a363f507fc39b96fc48d693665a823a358345326",
.hash = "1220fe42e39fd141c84fd7d5cf69945309bb47253033e68788f99bdfe5585fbc711a",
},
},
.dependencies = .{},
.paths = .{
"LICENSE",
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

View File

@@ -1,97 +0,0 @@
const std = @import("std");
const zterm = @import("zterm");
const App = zterm.App(union(enum) {});
const Key = zterm.Key;
const log = std.log.scoped(.example);
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(.{}){};
defer {
const deinit_status = gpa.deinit();
if (deinit_status == .leak) {
log.err("memory lead", .{});
}
}
const allocator = gpa.allocator();
var app: App = .{};
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var container = try App.Container.init(allocator, .{
.border = .{
.color = .blue,
.corners = .rounded,
.sides = .all(),
.separator = .{ .enabled = false },
},
.layout = .{
.gap = 1,
.padding = .all(5),
.direction = .horizontal,
},
});
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.layout = .{
.sizing = .{
.width = .{ .fixed = 70 },
.height = .{ .fixed = 18 },
},
},
}));
try container.append(try App.Container.init(allocator, .{
.border = .{ .color = .light_blue, .corners = .squared },
}));
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
}));
defer container.deinit();
// NOTE: should the min-size here be required?
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.matches(.{ .cp = 'q' })) app.quit();
if (key.matches(.{ .cp = 'n', .mod = .{ .ctrl = true } })) {
try app.interrupt();
defer app.start() catch @panic("could not start app event loop");
var child = std.process.Child.init(&.{"hx"}, allocator);
_ = child.spawnAndWait() catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Spawning $EDITOR failed",
},
});
}
},
.err => |err| {
log.err("Received {any} with message: {s}", .{ @errorName(err.err), err.msg });
},
else => {},
}
try container.handle(event);
try renderer.render(@TypeOf(container), &container);
try renderer.flush();
}
}

247
examples/continuous.zig Normal file
View File

@@ -0,0 +1,247 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
/// Spinner element implementation that runs a simple animation that requires
/// the continuous draw loop.
const Spinner = struct {
counter: u8 = 0,
index: u8 = 0,
const map: [6]u21 = .{ '𜺎', '𜺍', '𜺇', '𜹯', '𜹿', '𜺋' };
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.content = content,
},
};
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
cells[size.x + 1].cp = map[this.index];
this.counter += 1;
if (this.counter >= 20) {
this.index += 1;
this.index %= 6;
this.counter = 0;
}
}
};
const InputField = struct {
allocator: std.mem.Allocator,
input: std.ArrayList(u21),
queue: *App.Queue,
pub fn init(allocator: std.mem.Allocator, queue: *App.Queue) @This() {
return .{
.allocator = allocator,
.input = std.ArrayList(u21).initCapacity(allocator, 8) catch unreachable,
.queue = queue,
};
}
pub fn deinit(this: *@This()) void {
this.input.deinit(this.allocator);
}
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
fn handle(ctx: *anyopaque, _: *App.Model, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.key => |key| {
if (key.isUnicode()) try this.input.append(this.allocator, key.cp);
if (key.eql(.{ .cp = zterm.input.Enter }) or key.eql(.{ .cp = zterm.input.KpEnter }))
this.queue.push(.{ .accept = try this.input.toOwnedSlice(this.allocator) });
if (key.eql(.{ .cp = zterm.input.Backspace }))
_ = this.input.pop();
if (key.eql(.{ .cp = zterm.input.Delete }) or key.eql(.{ .cp = zterm.input.KpDelete }))
_ = this.input.pop();
},
else => {},
}
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
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.x) + col;
for (this.input.items, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .black;
cells[anchor + idx].style.cursor = false;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
if (idx == this.input.items.len - 1) cells[anchor + idx + 1].style.cursor = true;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var input_field: InputField = .init(allocator, &app.queue);
defer input_field.deinit();
var quit_text: QuitText = .{};
var spinner: Spinner = .{};
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{
.direction = .vertical,
.padding = .all(5),
},
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgrey },
.size = .{
.grow = .horizontal,
.dim = .{ .y = 10 },
},
}, input_field.element()));
const nested_container: App.Container = try .init(allocator, .{
.rectangle = .{ .fill = .lightgrey },
}, spinner.element());
try container.append(nested_container);
try app.start(.full);
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
var framerate: u64 = 60;
var tick_ms: u64 = @divFloor(time.ms_per_s, framerate);
var next_frame_ms: u64 = 0;
// draw loop
draw: while (true) {
const now_ms: u64 = @intCast(time.milliTimestamp());
if (now_ms >= next_frame_ms) {
next_frame_ms = now_ms + tick_ms;
} else {
std.Thread.sleep((next_frame_ms - now_ms) * time.ns_per_ms);
next_frame_ms += tick_ms;
}
const len = blk: {
app.queue.lock();
defer app.queue.unlock();
break :blk app.queue.len();
};
// handle events
for (0..len) |_| {
const event = app.queue.drain() orelse break;
log.debug("handling event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.key => |key| {
log.debug("key {any}", .{key});
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
},
.accept => |input| {
defer allocator.free(input);
var string = try allocator.alloc(u8, input.len);
defer allocator.free(string);
for (0.., input) |i, char| string[i] = @intCast(char);
log.debug("Accepted input '{s}'", .{string});
},
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
.focus => |b| {
// NOTE reduce framerate in case the window is not focused and restore again when focused
framerate = if (b) 60 else 15;
tick_ms = @divFloor(time.ms_per_s, framerate);
},
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break :draw,
else => {},
}
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const time = std.time;
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {
accept: []u21,
});

196
examples/demo.zig Normal file
View File

@@ -0,0 +1,196 @@
const QuitText = struct {
const text = "Press ctrl+c to quit. Press ctrl+n to launch `vim`.";
pub fn element(this: *@This()) App.Element {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
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`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var quit_text: QuitText = .{};
// 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 },
},
}, .{});
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
}, .{}));
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
}, .{}));
try box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
}, .{}));
var scrollable: App.Scrollable = .init(box, .disabled);
var container = try App.Container.init(allocator, .{
.layout = .{
.gap = 2,
.separator = .{ .enabled = true },
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .horizontal,
},
}, quit_text.element());
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
var nested_container: App.Container = try .init(allocator, .{
.layout = .{
.direction = .vertical,
.separator = .{
.enabled = true,
},
},
}, .{});
var inner_container: App.Container = try .init(allocator, .{
.layout = .{
.direction = .vertical,
},
.border = .{
.color = .lightblue,
.sides = .all,
},
}, .{});
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .blue,
},
.size = .{
.grow = .horizontal,
.dim = .{ .y = 5 },
},
}, .{}));
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .red,
},
.size = .{
.grow = .horizontal,
.dim = .{ .y = 5 },
},
}, .{}));
try inner_container.append(try .init(allocator, .{
.rectangle = .{
.fill = .green,
},
}, .{}));
try nested_container.append(inner_container);
try nested_container.append(try .init(allocator, .{
.size = .{
.grow = .horizontal,
.dim = .{ .y = 1 },
},
}, .{}));
try container.append(nested_container);
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.size = .{
.dim = .{ .x = 30 },
},
}, .{}));
defer container.deinit(); // also de-initializes the children
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| {
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
if (key.eql(.{ .cp = 'n', .mod = .{ .ctrl = true } })) {
try app.interrupt();
renderer.size = .{}; // reset size, such that next resize will cause a full re-draw!
defer app.start(.full) catch @panic("could not start app event loop");
var child = std.process.Child.init(&.{"vim"}, allocator);
_ = child.spawnAndWait() catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Spawning $EDITOR failed",
},
});
continue;
}
},
// 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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const input = zterm.input;
const App = zterm.App(struct {}, union(enum) {});

192
examples/direct.zig Normal file
View File

@@ -0,0 +1,192 @@
const QuitText = struct {
const text = "Press ctrl+c to quit.";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.minSize = minSize,
.content = content,
},
};
}
fn minSize(_: *anyopaque, _: *const App.Model, size: zterm.Point) zterm.Point {
return .{ .x = size.x, .y = 10 }; // this includes the border
}
pub fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const y = 0;
const x = 2;
const anchor = (y * size.x) + x;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.emphasis = &.{ .bold, .underline };
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 Prompt = struct {
len: u16 = 3,
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
// .minSize = minSize,
.content = content,
},
};
}
// NOTE size hint is not required as the `.size = .{ .dim = .{..} }` property is set accordingly which denotes the minimal size
// fn minSize(ctx: *anyopaque, _: *const App.Model, _: zterm.Point) zterm.Point {
// const this: *@This() = @ptrCast(@alignCast(ctx));
// return .{ .x = this.len, .y = 1 };
// }
pub fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
assert(cells.len > 2); // expect at least two cells
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
for (0..this.len) |idx| {
cells[idx].style.bg = .blue;
cells[idx].style.fg = .black;
cells[idx].style.emphasis = &.{.bold};
}
cells[1].cp = '>';
// leave one clear whitespace after the prompt
cells[this.len].style.bg = .default;
cells[this.len].style.cursor = true; // marks the actual end of the rendering!
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var allocator: std.heap.DebugAllocator(.{}) = .init;
defer if (allocator.deinit() == .leak) log.err("memory leak", .{});
const gpa = allocator.allocator();
var app: App = .init(gpa, .{}, .{});
var renderer = zterm.Renderer.Direct.init(gpa);
defer renderer.deinit();
var container: App.Container = try .init(gpa, .{
.layout = .{
.direction = .vertical,
.gap = 1, // show empty line between elements to allow navigation through paragraph jumping
},
.size = .{
.grow = .horizontal_only,
},
}, .{});
defer container.deinit();
var quit_text: QuitText = .{};
var intermediate: App.Container = try .init(gpa, .{
.border = .{
.sides = .{ .left = true },
.color = .grey,
},
.layout = .{
.direction = .horizontal,
.padding = .{ .left = 1, .top = 1 },
},
}, quit_text.element());
try intermediate.append(try .init(gpa, .{
.rectangle = .{ .fill = .blue },
}, .{}));
try intermediate.append(try .init(gpa, .{
.rectangle = .{ .fill = .green },
}, .{}));
var padding_container: App.Container = try .init(gpa, .{
.layout = .{
.padding = .horizontal(1),
},
}, .{});
try padding_container.append(intermediate);
try container.append(padding_container);
var prompt: Prompt = .{};
try container.append(try .init(gpa, .{
.rectangle = .{ .fill = .grey },
.size = .{
.dim = .{ .y = 1 },
},
}, prompt.element()));
try app.start(.direct); // needs to become configurable, as what should be enabled / disabled (i.e. show cursor, hide cursor, use alternate screen, etc.)
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
event: while (true) {
// batch events since last iteration
const len = blk: {
app.queue.poll();
app.queue.lock();
defer app.queue.unlock();
break :blk app.queue.len();
};
// handle events
for (0..len) |_| {
const event = app.queue.pop();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
// NOTE draw the character with the ctrl indication and a newline to make sure the rendering stays consistent
.cancel => try renderer.writeCtrlDWithNewline(),
.line => |line| {
defer gpa.free(line);
log.debug("{s}", .{line});
},
// 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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break :event,
else => {},
}
}
// if there are more events to process continue handling them otherwise I can render the next frame
if (app.queue.len() > 0) continue :event;
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const input = zterm.input;
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -0,0 +1,99 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var container: App.Container = try .init(allocator, .{}, .{});
defer container.deinit();
var quit_text: QuitText = .{};
const quit_container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .blue },
.layout = .{
.direction = .vertical,
.padding = .all(5),
},
.size = .{
.dim = .{ .x = 25, .y = 5 },
.grow = .fixed,
},
}, quit_text.element());
var alignment: App.Alignment = .init(quit_container, .center);
try container.append(try .init(allocator, .{}, alignment.element()));
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -0,0 +1,154 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const Clickable = struct {
const text = "Press me";
queue: *App.Queue,
color: zterm.Color = .black,
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
fn handle(ctx: *anyopaque, _: *App.Model, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
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 = 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`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var clickable: Clickable = .{ .queue = &app.queue };
const element = clickable.element();
var button: App.Button(.accept) = .init(&app.queue, .init(.default, "Button"));
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{ .padding = .all(5) },
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .lightgrey } }, element));
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .black } }, button.element()));
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.click => |b| log.info("Clicked with mouse using Button: {s}", .{b}),
.accept => log.info("Clicked built-in button using the mouse", .{}),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(
struct {},
union(enum) {
click: [:0]const u8,
accept,
},
);

167
examples/elements/input.zig Normal file
View File

@@ -0,0 +1,167 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const MouseDraw = struct {
position: ?zterm.Point = null,
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
fn handle(ctx: *anyopaque, _: *App.Model, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.mouse => |mouse| this.position = .{ .x = mouse.x, .y = mouse.y },
else => this.position = null,
}
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const this: *@This() = @ptrCast(@alignCast(ctx));
if (this.position) |pos| {
const idx = @as(usize, size.x) * @as(usize, pos.y) + @as(usize, pos.x);
cells[idx].cp = 'x';
cells[idx].style.fg = .red;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var input_field: App.Input(.accept) = .init(allocator, &app.queue, .init(.black, .blue));
var mouse_draw: MouseDraw = .{};
var second_mouse_draw: MouseDraw = .{};
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{
.direction = .vertical,
.padding = .all(5),
},
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgrey },
.size = .{
.grow = .horizontal,
.dim = .{ .y = 1 },
},
}, input_field.element()));
var nested_container: App.Container = try .init(allocator, .{
.border = .{
.sides = .all,
.color = .black,
},
.rectangle = .{ .fill = .lightgrey },
.layout = .{
.separator = .{
.enabled = true,
.color = .black,
},
},
}, .{});
try nested_container.append(try .init(allocator, .{
.rectangle = .{ .fill = .lightgrey },
}, mouse_draw.element()));
try nested_container.append(try .init(allocator, .{
.rectangle = .{ .fill = .lightgrey },
}, second_mouse_draw.element()));
try container.append(nested_container);
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.accept => |input| {
defer allocator.free(input);
log.debug("Accepted input '{s}'", .{input});
},
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const Color = zterm.Color;
const App = zterm.App(
struct {},
union(enum) {
accept: []u8,
},
);

View File

@@ -0,0 +1,174 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var progress_percent: u8 = 0;
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
.layout = .{ .padding = .all(5), .direction = .vertical },
}, quit_text.element());
defer container.deinit();
{
var progress: App.Progress(.progress) = .init(&app.queue, .{
.percent = .{
.enabled = true,
.alignment = .left,
},
.fg = .blue,
.bg = .grey,
});
try container.append(try App.Container.init(allocator, .{}, progress.element()));
}
{
var progress: App.Progress(.progress) = .init(&app.queue, .{
.percent = .{
.enabled = true,
.alignment = .middle, // default
},
.fg = .red,
.bg = .grey,
});
try container.append(try App.Container.init(allocator, .{}, progress.element()));
}
{
var progress: App.Progress(.progress) = .init(&app.queue, .{
.percent = .{
.enabled = true,
.alignment = .right,
},
.fg = .green,
.bg = .grey,
});
try container.append(try App.Container.init(allocator, .{}, progress.element()));
}
{
var progress: App.Progress(.progress) = .init(&app.queue, .{
.percent = .{ .enabled = false },
.fg = .default,
.bg = .grey,
});
try container.append(try App.Container.init(allocator, .{}, progress.element()));
}
try app.start(.full);
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
var framerate: u64 = 60;
var tick_ms: u64 = @divFloor(time.ms_per_s, framerate);
var next_frame_ms: u64 = 0;
var increase_progress: u64 = 10;
// Continuous drawing
// draw loop
draw: while (true) {
const now_ms: u64 = @intCast(time.milliTimestamp());
if (now_ms >= next_frame_ms) {
next_frame_ms = now_ms + tick_ms;
} else {
std.Thread.sleep((next_frame_ms - now_ms) * time.ns_per_ms);
next_frame_ms += tick_ms;
}
// NOTE time based progress increasion
increase_progress -= 1;
if (increase_progress == 0) {
increase_progress = 10;
progress_percent += 1;
if (progress_percent > 100) progress_percent = 0;
app.postEvent(.{ .progress = progress_percent });
}
const len = blk: {
app.queue.lock();
defer app.queue.unlock();
break :blk app.queue.len();
};
// handle events
for (0..len) |_| {
const event = app.queue.drain() orelse break;
log.debug("handling event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.key => |key| {
if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit();
},
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
.focus => |b| {
// NOTE reduce framerate in case the window is not focused and restore again when focused
framerate = if (b) 60 else 15;
tick_ms = @divFloor(time.ms_per_s, framerate);
},
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break :draw,
else => {},
}
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const time = std.time;
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(
struct {},
union(enum) {
progress: u8,
},
);

View File

@@ -0,0 +1,98 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var radiobutton: App.RadioButton = .init(false, .{
.label = "Test Radio Button",
.style = .squared,
});
var button: App.Button(.accept) = .init(&app.queue, .init(.default, "Button"));
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 .init(allocator, .{}, radiobutton.element()));
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .black } }, button.element()));
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.accept => log.info("Clicked built-in button using the mouse", .{}),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {
accept,
});

View File

@@ -0,0 +1,196 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const HelloWorldText = packed struct {
const text = "Hello World";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{ .content = content },
};
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = size.y / 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer {
const deinit_status = gpa.deinit();
if (deinit_status == .leak) {
log.err("memory leak", .{});
}
}
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
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 = 2,
.separator = .{
.enabled = true,
},
.direction = .vertical,
.padding = .vertical(1),
},
}, .{});
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
.size = .{
.dim = .{ .y = 30 },
},
}, .{}));
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
.size = .{
.dim = .{ .y = 5 },
},
}, element));
try top_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .lightgreen },
.size = .{
.dim = .{ .y = 2 },
},
}, .{}));
var bottom_box = try App.Container.init(allocator, .{
.border = .{
.sides = .all,
.color = .blue,
},
.layout = .{
.separator = .{
.enabled = true,
.color = .red,
},
.direction = .vertical,
.padding = .vertical(1),
},
.size = .{
.dim = .{ .y = 30 },
},
}, .{});
try bottom_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
try bottom_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
}, element));
try bottom_box.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
}, .{}));
var container = try App.Container.init(allocator, .{
.layout = .{
.gap = 2,
.separator = .{
.enabled = true,
.line = .double,
},
.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, .enabled(.default, false));
try container.append(try App.Container.init(allocator, .{}, scrollable_top.element()));
var scrollable_bottom: App.Scrollable = .init(bottom_box, .enabled(.white, true));
try container.append(try App.Container.init(allocator, .{}, scrollable_bottom.element()));
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const input = zterm.input;
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -0,0 +1,97 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var selection: App.Selection(enum {
one,
two,
three,
}) = .init(.{
.label = "Selection",
});
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 .init(allocator, .{}, selection.element()));
try app.start(.full);
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)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const Error = zterm.Error;
const App = zterm.App(struct {}, union(enum) {});

159
examples/errors.zig Normal file
View File

@@ -0,0 +1,159 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const InfoText = struct {
const text = "Press any key; Non-Ascii inputs (i.e. `Enter` or `Backspace`) to trigger an exception";
pub fn element(this: *@This()) App.Element {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const ErrorNotification = struct {
msg: ?[]const u8 = null,
pub fn element(this: *@This()) App.Element {
return .{ .ptr = this, .vtable = &.{ .handle = handle, .content = content } };
}
fn handle(ctx: *anyopaque, _: *App.Model, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.key => |key| if (!key.isAscii()) return zterm.Error.TooSmall,
.err => |err| this.msg = err.msg,
else => {},
}
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
if (this.msg) |msg| {
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`
if (anchor + idx == cells.len - 1) break;
}
this.msg = null;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var quit_text: QuitText = .{};
var info_text: InfoText = .{};
var error_notification: ErrorNotification = .{};
var container = try App.Container.init(allocator, .{
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
},
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{}, info_text.element()));
try container.append(try App.Container.init(allocator, .{}, error_notification.element()));
try app.start(.full);
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

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

@@ -0,0 +1,115 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
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, .{
.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, .{
.layout = .{
.separator = .{ .enabled = true },
.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(.full);
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)});
// pre event handling
switch (event) {
.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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -0,0 +1,107 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
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(.full);
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)});
// pre event handling
switch (event) {
.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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

123
examples/layouts/mixed.zig Normal file
View File

@@ -0,0 +1,123 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
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, .{
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
},
}, element);
for (0..3) |i| {
var column = try App.Container.init(allocator, .{
.layout = .{
.separator = .{ .enabled = true },
.direction = if (i > 0) .vertical else .horizontal,
},
}, .{});
if (i != 1) {
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .green },
}, .{}));
try column.append(try App.Container.init(allocator, .{
.rectangle = .{ .fill = .yellow },
}, .{}));
} else {
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 },
}, .{}));
try container.append(column);
}
defer container.deinit(); // also de-initializes the children
try app.start(.full);
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)});
// pre event handling
switch (event) {
.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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -0,0 +1,106 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
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, .{
.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(.full);
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)});
// pre event handling
switch (event) {
.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(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

101
examples/styles/palette.zig Normal file
View File

@@ -0,0 +1,101 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
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, .{
.layout = .{
.gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
},
}, element);
defer container.deinit();
var box = try App.Container.init(allocator, .{
.layout = .{ .direction = .horizontal },
}, .{});
inline for (std.meta.fields(zterm.Color)) |field| {
if (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, .disabled);
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
try app.start(.full);
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
while (true) {
const event = app.nextEvent();
log.debug("received event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break,
else => {},
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

264
examples/styles/text.zig Normal file
View File

@@ -0,0 +1,264 @@
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, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
const row = 2;
const col = size.x / 2 -| (text.len / 2);
const anchor = (row * size.x) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const TableText = struct {
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.content = content,
},
};
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
_ = ctx;
_ = size;
var idx: usize = 0;
{
const text = "Normal ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Bold ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Dim ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Italic ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Underl ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Blink ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Invert ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Hidden ";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
{
const text = "Strikethrough";
for (text) |cp| {
cells[idx].cp = cp;
idx += 1;
}
}
}
};
const TextStyles = struct {
const text = "Example";
pub fn element(this: *@This()) App.Element {
return .{
.ptr = this,
.vtable = &.{
.minSize = minSize,
.content = content,
},
};
}
fn minSize(ctx: *anyopaque, _: *const App.Model, size: zterm.Point) zterm.Point {
_ = ctx;
_ = size;
return .{
.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),
};
}
fn content(ctx: *anyopaque, _: *const App.Model, cells: []zterm.Cell, size: zterm.Point) !void {
@setEvalBranchQuota(10000);
_ = ctx;
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
var row: usize = 0;
var col: usize = 0;
// Color
inline for (std.meta.fields(zterm.Color)) |bg_field| {
if (bg_field.value == 0) continue; // zterm.Color.default == 0 -> skip
inline for (std.meta.fields(zterm.Color)) |fg_field| {
if (fg_field.value == 0) continue; // zterm.Color.default == 0 -> skip
if (fg_field.value == bg_field.value) continue;
// witouth any emphasis
for (text) |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;
}
// emphasis (no combinations)
inline for (std.meta.fields(zterm.Style.Emphasis)) |emp_field| {
if (emp_field.value == 0) continue; // zterm.Style.Emphasis.reset == 0 -> skip
const emphasis: zterm.Style.Emphasis = @enumFromInt(emp_field.value);
for (text) |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;
}
}
row += 1;
col = 0;
}
}
}
};
pub fn main() !void {
errdefer |err| log.err("Application Error: {any}", .{err});
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer if (gpa.deinit() == .leak) log.err("memory leak", .{});
const allocator = gpa.allocator();
var app: App = .init(allocator, .{}, .{});
var renderer = zterm.Renderer.Buffered.init(allocator);
defer renderer.deinit();
var quit_text: QuitText = .{};
const element = quit_text.element();
var text_styles: TextStyles = .{};
var container = try App.Container.init(allocator, .{
.layout = .{
// .gap = 2,
.padding = .{ .top = 5, .bottom = 3, .left = 3, .right = 3 },
.direction = .vertical,
},
}, element);
defer container.deinit();
var table_head: TableText = .{};
try container.append(try .init(allocator, .{
.size = .{
.dim = .{ .y = 1 },
.grow = .horizontal,
},
}, table_head.element()));
var scrollable: App.Scrollable = .init(try .init(allocator, .{
.layout = .{ .direction = .vertical },
}, text_styles.element()), .enabled(.white, true));
try container.append(try App.Container.init(allocator, .{}, scrollable.element()));
try app.start(.full);
defer app.stop() catch |err| log.err("Failed to stop application: {any}", .{err});
// event loop
loop: while (true) {
// batch events since last iteration
const len = blk: {
app.queue.poll();
app.queue.lock();
defer app.queue.unlock();
break :blk app.queue.len();
};
// handle events
for (0..len) |_| {
const event = app.queue.pop();
log.debug("handling event: {s}", .{@tagName(event)});
// pre event handling
switch (event) {
.key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit(),
.err => |err| log.err("Received {s} with message: {s}", .{ @errorName(err.err), err.msg }),
else => {},
}
container.handle(&app.model, event) catch |err| app.postEvent(.{
.err = .{
.err = err,
.msg = "Container Event handling failed",
},
});
// post event handling
switch (event) {
.quit => break :loop,
else => {},
}
}
container.resize(&app.model, try renderer.resize());
container.reposition(&app.model, .{});
try renderer.render(@TypeOf(container), &container, App.Model, &app.model);
try renderer.flush();
}
}
pub const panic = App.panic_handler;
const log = std.log.scoped(.default);
const std = @import("std");
const assert = std.debug.assert;
const zterm = @import("zterm");
const App = zterm.App(struct {}, union(enum) {});

View File

@@ -1,16 +1,4 @@
//! Application type for TUI-applications
const std = @import("std");
const terminal = @import("terminal.zig");
const event = @import("event.zig");
const mergeTaggedUnions = event.mergeTaggedUnions;
const isTaggedUnion = event.isTaggedUnion;
const Key = @import("key.zig");
const Size = @import("size.zig").Size;
const Queue = @import("queue.zig").Queue;
const log = std.log.scoped(.app);
/// Create the App Type with the associated user events _E_ which describes
/// an tagged union for all the user events that can be send through the
@@ -24,76 +12,118 @@ const log = std.log.scoped(.app);
/// ```zig
/// const zterm = @import("zterm");
/// const App = zterm.App(
/// union(enum) {},
/// struct {}, // empty model
/// union(enum) {}, // no additional user event's
/// );
/// // later on create an `App` instance and start the event loop
/// var app: App = .{};
/// try app.start(null);
/// defer app.stop() catch unreachable;
/// var app: App = .init(io, .{}); // provide instance of the `std.Io` and `App` model that shall be used
/// try app.start(.full);
/// defer app.stop() catch unreachable; // does not clean-up the resources used in the model
/// ```
pub fn App(comptime E: type) type {
if (!isTaggedUnion(E)) {
@compileError("Provided user event `E` for `App(comptime E: type)` is not of type `union(enum)`.");
}
pub fn App(comptime M: type, comptime E: type) type {
if (!isStruct(M)) @compileError("Provided model `M` for `App(comptime M: type, comptime E: type)` is not of type `struct`");
if (!isTaggedUnion(E)) @compileError("Provided user event `E` for `App(comptime M: type, comptime E: type)` is not of type `union(enum)`.");
return struct {
pub const Event = mergeTaggedUnions(event.SystemEvent, E);
pub const Container = @import("container.zig").Container(Event);
gpa: Allocator,
io: std.Io,
model: Model,
queue: Queue,
thread: ?Thread = null,
quit_event: Thread.ResetEvent,
termios: ?posix.termios = null,
handler_registered: bool = false,
config: TerminalConfiguration,
queue: Queue(Event, 256) = .{},
thread: ?std.Thread = null,
quit_event: std.Thread.ResetEvent = .{},
termios: ?std.posix.termios = null,
attached_handler: bool = false,
prev_size: Size = .{ .cols = 0, .rows = 0 },
pub const TerminalConfiguration = struct {
altScreen: bool,
saveScreen: bool,
rawMode: bool,
hideCursor: bool,
pub const SignalHandler = struct {
context: *anyopaque,
callback: *const fn (context: *anyopaque) void,
pub const full: @This() = .{
.altScreen = true,
.saveScreen = true,
.rawMode = true,
.hideCursor = true,
};
pub const direct: @This() = .{
.altScreen = false,
.saveScreen = false,
.rawMode = false,
.hideCursor = false,
};
};
pub fn start(this: *@This()) !void {
// global variable for the registered handler for WINCH
var handler_ctx: *anyopaque = undefined;
/// registered WINCH handler to report resize events
fn handleWinch(_: i32) callconv(.c) void {
const this: *@This() = @ptrCast(@alignCast(handler_ctx));
// NOTE this does not have to be done if in-band resize events are supported
// -> the signal might not work correctly when hosting the application over ssh!
this.postEvent(.resize);
}
/// registered CONT handler to force a complete redraw
fn handleCont(_: i32) callconv(.c) void {
const this: *@This() = @ptrCast(@alignCast(handler_ctx));
// NOTE this does not have to be done if in-band resize events are supported
// -> the signal might not work correctly when hosting the application over ssh!
this.postEvent(.resize);
}
pub fn init(gpa: Allocator, io: std.Io, model: Model) @This() {
return .{
.gpa = gpa,
.io = io,
.model = model,
.queue = .{},
.quit_event = .{},
.config = undefined,
};
}
pub fn start(this: *@This(), config: TerminalConfiguration) !void {
this.config = config;
if (this.thread) |_| return;
if (!this.attached_handler) {
var winch_act = std.posix.Sigaction{
.handler = .{ .handler = @This().handleWinch },
.mask = std.posix.empty_sigset,
// post init event (as the very first element to be in the queue - event loop)
this.postEvent(.init);
if (!this.handler_registered) {
handler_ctx = this;
posix.sigaction(posix.SIG.WINCH, &.{
.handler = .{ .handler = handleWinch },
.mask = posix.sigemptyset(),
.flags = 0,
};
std.posix.sigaction(std.posix.SIG.WINCH, &winch_act, null);
try registerWinch(.{
.context = this,
.callback = @This().winsizeCallback,
});
this.attached_handler = true;
// post init event (as the very first element to be in the queue - event loop)
this.postEvent(.init);
}, null);
posix.sigaction(posix.SIG.CONT, &.{
.handler = .{ .handler = handleCont },
.mask = posix.sigemptyset(),
.flags = 0,
}, null);
this.handler_registered = true;
}
this.quit_event.reset();
this.thread = try std.Thread.spawn(.{}, @This().run, .{this});
this.thread = try Thread.spawn(.{}, @This().run, .{this});
var termios: std.posix.termios = undefined;
try terminal.enableRawMode(&termios);
var termios: posix.termios = undefined;
if (this.config.rawMode) try terminal.enableRawMode(&termios);
if (this.termios) |_| {} else this.termios = termios;
try terminal.saveScreen();
try terminal.enterAltScreen();
try terminal.hideCursor();
// send initial size afterwards
const size = terminal.getTerminalSize();
this.postEvent(.{ .resize = size });
this.prev_size = size;
if (this.config.altScreen) try terminal.enterAltScreen();
if (this.config.saveScreen) try terminal.saveScreen();
if (this.config.hideCursor) try terminal.hideCursor();
if (this.config.altScreen and this.config.rawMode) try terminal.enableMouseSupport();
}
pub fn interrupt(this: *@This()) !void {
this.quit_event.set();
try terminal.exitAltScreen();
try terminal.restoreScreen();
if (this.thread) |thread| {
if (this.config.altScreen and this.config.rawMode) try terminal.disableMouseSupport();
if (this.config.saveScreen) try terminal.restoreScreen();
if (this.config.altScreen) try terminal.exitAltScreen();
if (this.thread) |*thread| {
thread.join();
this.thread = null;
}
@@ -101,17 +131,16 @@ pub fn App(comptime E: type) type {
pub fn stop(this: *@This()) !void {
try this.interrupt();
if (this.termios) |*termios| {
try terminal.disableRawMode(termios);
try terminal.showCursor();
try terminal.exitAltScreen();
try terminal.restoreScreen();
if (this.config.hideCursor) try terminal.showCursor();
if (this.config.saveScreen) try terminal.resetCursor();
if (this.termios) |termios| {
if (this.config.rawMode) try terminal.disableRawMode(&termios);
this.termios = null;
}
this.termios = null;
}
/// Quit the application loop.
/// This will stop the internal input thread and post a **.quit** `Event`.
/// This will cancel the internal input thread and post a **.quit** `Event`.
pub fn quit(this: *@This()) void {
this.quit_event.set();
this.postEvent(.quit);
@@ -127,72 +156,83 @@ pub fn App(comptime E: type) type {
this.queue.push(e);
}
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;
}
}
var winch_handler: ?SignalHandler = null;
fn registerWinch(handler: SignalHandler) !void {
if (winch_handler) |_| {
@panic("Cannot register another WINCH handler.");
}
winch_handler = handler;
}
fn handleWinch(_: c_int) callconv(.C) void {
if (winch_handler) |handler| {
handler.callback(handler.context);
}
}
fn run(this: *@This()) !void {
// send initial terminal size
// changes are handled by the winch signal handler
// see `App.start` and `App.registerWinch` for details
{}
// thread to read user inputs
var buf: [256]u8 = undefined;
var buf: [512]u8 = undefined;
// NOTE set the `NONBLOCK` option for the stdin file, such that reading is not blocking!
if (this.config.rawMode) {
// TODO is there a better way to do this through the `std.Io` interface?
var fl_flags = posix.fcntl(posix.STDIN_FILENO, posix.F.GETFL, 0) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
fl_flags |= 1 << @bitOffsetOf(posix.system.O, "NONBLOCK");
_ = posix.fcntl(posix.STDIN_FILENO, posix.F.SETFL, fl_flags) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
}
var remaining_bytes: usize = 0;
var lines: std.ArrayList(u8) = .empty;
defer lines.deinit(this.gpa);
while (true) {
// 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 {
const read_bytes = try terminal.read(buf[0..]);
// non-blocking read
const read_bytes = terminal.read(buf[remaining_bytes..]) catch |err| switch (err) {
error.WouldBlock => {
// wait a bit
std.Thread.sleep(20);
continue;
},
else => return err,
} + remaining_bytes;
remaining_bytes = 0;
if (read_bytes == 0) {
// received <EOF>
this.postEvent(.cancel);
continue;
}
// escape key presses
if (buf[0] == 0x1b and read_bytes > 1) {
switch (buf[1]) {
0x4F => { // ss3
if (read_bytes < 3) continue;
const key: ?Key = switch (buf[2]) {
0x1B => null,
'A' => .{ .cp = Key.up },
'B' => .{ .cp = Key.down },
'C' => .{ .cp = Key.right },
'D' => .{ .cp = Key.left },
'E' => .{ .cp = Key.kp_begin },
'F' => .{ .cp = Key.end },
'H' => .{ .cp = Key.home },
'P' => .{ .cp = Key.f1 },
'Q' => .{ .cp = Key.f2 },
'R' => .{ .cp = Key.f3 },
'S' => .{ .cp = Key.f4 },
else => null,
const key: Key = switch (buf[2]) {
'A' => .{ .cp = input.Up },
'B' => .{ .cp = input.Down },
'C' => .{ .cp = input.Right },
'D' => .{ .cp = input.Left },
'E' => .{ .cp = input.KpBegin },
'F' => .{ .cp = input.End },
'H' => .{ .cp = input.Home },
'P' => .{ .cp = input.F1 },
'Q' => .{ .cp = input.F2 },
'R' => .{ .cp = input.F3 },
'S' => .{ .cp = input.F4 },
else => continue,
};
if (key) |k| this.postEvent(.{ .key = k });
this.postEvent(.{ .key = key });
},
0x5B => { // csi
if (read_bytes < 3) continue;
// We start iterating at index 2 to get past the '['
const sequence = for (buf[2..], 2..) |b, i| {
const sequence: []u8 = blk: for (buf[2..], 2..) |b, i| {
switch (b) {
0x40...0xFF => break buf[0 .. i + 1],
0x40...0xFF => break :blk buf[0 .. i + 1],
else => continue,
}
} else continue;
@@ -203,64 +243,140 @@ pub fn App(comptime E: type) type {
// Legacy keys
// CSI {ABCDEFHPQS}
// CSI 1 ; modifier:event_type {ABCDEFHPQS}
var field_iter = std.mem.splitScalar(u8, sequence[2 .. sequence.len - 1], ';');
_ = field_iter.next(); // skip first field
const key: Key = .{
.cp = switch (final) {
'A' => Key.up,
'B' => Key.down,
'C' => Key.right,
'D' => Key.left,
'E' => Key.kp_begin,
'F' => Key.end,
'H' => Key.home,
'P' => Key.f1,
'Q' => Key.f2,
'R' => Key.f3,
'S' => Key.f4,
else => unreachable, // switch case prevents in this case form ever happening
'A' => input.Up,
'B' => input.Down,
'C' => input.Right,
'D' => input.Left,
'E' => input.KpBegin,
'F' => input.End,
'H' => input.Home,
'P' => input.F1,
'Q' => input.F2,
'R' => input.F3,
'S' => input.F4,
else => unreachable,
},
.mod = blk: {
// modifier_mask:event_type
var mod: Key.Modifier = .{};
const field_buf = field_iter.next() orelse break :blk mod;
var param_iter = std.mem.splitScalar(u8, field_buf, ':');
const modifier_buf = param_iter.next() orelse unreachable;
const modifier_mask = fmt.parseUnsigned(u8, modifier_buf, 10) catch break :blk mod;
if ((modifier_mask -| 1) & 1 != 0) mod.shift = true;
if ((modifier_mask -| 1) & 2 != 0) mod.alt = true;
if ((modifier_mask -| 1) & 4 != 0) mod.ctrl = true;
break :blk mod;
},
};
this.postEvent(.{ .key = key });
},
'Z' => this.postEvent(.{ .key = .{ .cp = input.Tab, .mod = .{ .shift = true } } }),
'~' => {
// Legacy keys
// CSI number ~
// CSI number ; modifier ~
// CSI number ; modifier:event_type ; text_as_codepoint ~
var field_iter = std.mem.splitScalar(u8, sequence[2 .. sequence.len - 1], ';');
const number_buf = field_iter.next() orelse unreachable; // always will have one field
const number = std.fmt.parseUnsigned(u16, number_buf, 10) catch break;
var field_iter = mem.splitScalar(u8, sequence[2 .. sequence.len - 1], ';');
const key: Key = .{
.cp = switch (number) {
2 => Key.insert,
3 => Key.delete,
5 => Key.page_up,
6 => Key.page_down,
7 => Key.home,
8 => Key.end,
11 => Key.f1,
12 => Key.f2,
13 => Key.f3,
14 => Key.f4,
15 => Key.f5,
17 => Key.f6,
18 => Key.f7,
19 => Key.f8,
20 => Key.f9,
21 => Key.f10,
23 => Key.f11,
24 => Key.f12,
// 200 => return .{ .event = .paste_start, .n = sequence.len },
// 201 => return .{ .event = .paste_end, .n = sequence.len },
57427 => Key.kp_begin,
else => unreachable,
.cp = blk: {
const number_buf = field_iter.next() orelse unreachable; // always will have one field
const number = fmt.parseUnsigned(u16, number_buf, 10) catch break;
break :blk switch (number) {
2 => input.Insert,
3 => input.Delete,
5 => input.PageUp,
6 => input.PageDown,
7 => input.Home,
8 => input.End,
11 => input.F1,
12 => input.F2,
13 => input.F3,
14 => input.F4,
15 => input.F5,
17 => input.F6,
18 => input.F7,
19 => input.F8,
20 => input.F9,
21 => input.F10,
23 => input.F11,
24 => input.F12,
25 => input.F13,
26 => input.F14,
28 => input.F15,
29 => input.F16,
31 => input.F17,
32 => input.F18,
33 => input.F19,
34 => input.F20,
// 200 => return .{ .event = .paste_start, .n = sequence.len },
// 201 => return .{ .event = .paste_end, .n = sequence.len },
57399...57454 => |code| code,
else => unreachable,
};
},
.mod = blk: {
// modifier_mask:event_type
var mod: Key.Modifier = .{};
const field_buf = field_iter.next() orelse break :blk mod;
var param_iter = std.mem.splitScalar(u8, field_buf, ':');
const modifier_buf = param_iter.next() orelse unreachable;
const modifier_mask = fmt.parseUnsigned(u8, modifier_buf, 10) catch break :blk mod;
if ((modifier_mask -| 1) & 1 != 0) mod.shift = true;
if ((modifier_mask -| 1) & 2 != 0) mod.alt = true;
if ((modifier_mask -| 1) & 4 != 0) mod.ctrl = true;
break :blk mod;
},
};
this.postEvent(.{ .key = key });
},
// TODO focus usage? should this even be in the default event system?
'I' => this.postEvent(.{ .focus = true }),
'O' => this.postEvent(.{ .focus = false }),
// 'M', 'm' => return parseMouse(sequence), // TODO: parse mouse inputs
'M', 'm' => {
assert(sequence.len >= 4);
if (sequence[2] != '<') break;
const delim1 = mem.indexOfScalarPos(u8, sequence, 3, ';') orelse break;
const button_mask = fmt.parseUnsigned(u16, sequence[3..delim1], 10) catch break;
const delim2 = mem.indexOfScalarPos(u8, sequence, delim1 + 1, ';') orelse break;
const px = fmt.parseUnsigned(u16, sequence[delim1 + 1 .. delim2], 10) catch break;
const py = fmt.parseUnsigned(u16, sequence[delim2 + 1 .. sequence.len - 1], 10) catch break;
const mouse_bits = packed struct {
const motion: u8 = 0b00100000;
const buttons: u8 = 0b11000011;
const shift: u8 = 0b00000100;
const alt: u8 = 0b00001000;
const ctrl: u8 = 0b00010000;
};
const button: Mouse.Button = @enumFromInt(button_mask & mouse_bits.buttons);
const motion = button_mask & mouse_bits.motion > 0;
// const shift = button_mask & mouse_bits.shift > 0;
// const alt = button_mask & mouse_bits.alt > 0;
// const ctrl = button_mask & mouse_bits.ctrl > 0;
this.postEvent(.{
.mouse = .{
.button = button,
.x = px -| 1,
.y = py -| 1,
.kind = blk: {
if (motion and button != Mouse.Button.none) break :blk .drag;
if (motion and button == Mouse.Button.none) break :blk .motion;
if (sequence[sequence.len - 1] == 'm') break :blk .release;
break :blk .press;
},
},
});
},
'c' => {
// Primary DA (CSI ? Pm c)
},
@@ -268,29 +384,26 @@ pub fn App(comptime E: type) type {
// Device Status Report
// CSI Ps n
// CSI ? Ps n
std.debug.assert(sequence.len >= 3);
assert(sequence.len >= 3);
},
't' => {
// XTWINOPS
// Split first into fields delimited by ';'
var iter = std.mem.splitScalar(u8, sequence[2 .. sequence.len - 1], ';');
var iter = mem.splitScalar(u8, sequence[2 .. sequence.len - 1], ';');
const ps = iter.first();
if (std.mem.eql(u8, "48", ps)) {
if (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(.resize);
// this.postEvent(.{ .size = .{
// .x = fmt.parseUnsigned(u16, width_char, 10) catch break,
// .y = fmt.parseUnsigned(u16, height_char, 10) catch break,
// } });
}
},
'u' => {
@@ -305,35 +418,133 @@ pub fn App(comptime E: type) type {
else => {},
}
},
// TODO: parse corresponding codes
// 0x5B => parseCsi(input, &self.buf), // CSI see https://github.com/rockorager/libvaxis/blob/main/src/Parser.zig
else => {},
0x50 => {
// DCS
},
0x58 => {
// SOS
},
0x5D => {
// OSC
},
// TODO parse corresponding codes
0x5F => {
// APC
// parse for kitty graphics capabilities
},
else => {
// alt + <char> keypress
this.postEvent(.{
.key = .{
.cp = buf[1],
.mod = .{ .alt = true },
},
});
},
}
} else {
const b = buf[0];
const key: Key = switch (b) {
0x00 => .{ .cp = '@', .mod = .{ .ctrl = true } },
0x08 => .{ .cp = Key.backspace },
0x09 => .{ .cp = Key.tab },
0x0a, 0x0d => .{ .cp = Key.enter },
0x01...0x07, 0x0b...0x0c, 0x0e...0x1a => .{ .cp = b + 0x60, .mod = .{ .ctrl = true } },
0x1b => escape: {
std.debug.assert(read_bytes == 1);
break :escape .{ .cp = Key.escape };
},
0x7f => .{ .cp = Key.backspace },
else => {
var iter = terminal.code_point.Iterator{ .bytes = buf[0..read_bytes] };
while (iter.next()) |cp| this.postEvent(.{ .key = .{ .cp = cp.code } });
continue;
},
};
this.postEvent(.{ .key = key });
if (this.config.rawMode) {
const b = buf[0];
const key: Key = switch (b) {
0x00 => .{ .cp = '@', .mod = .{ .ctrl = true } },
0x08 => .{ .cp = input.Backspace },
0x09 => .{ .cp = input.Tab },
0x0a => .{ .cp = 'j', .mod = .{ .ctrl = true } },
0x0d => .{ .cp = input.Enter },
0x01...0x07, 0x0b...0x0c, 0x0e...0x1a => .{ .cp = b + 0x60, .mod = .{ .ctrl = true } },
0x1b => escape: {
assert(read_bytes == 1);
break :escape .{ .cp = input.Escape };
},
0x7f => .{ .cp = input.Backspace },
else => {
var len = read_bytes;
while (!std.unicode.utf8ValidateSlice(buf[0..len])) len -= 1;
remaining_bytes = read_bytes - len;
var iter: std.unicode.Utf8Iterator = .{ .bytes = buf[0..len], .i = 0 };
while (iter.nextCodepoint()) |cp| this.postEvent(.{ .key = .{ .cp = cp } });
if (remaining_bytes > 0) {
@memmove(buf[0..remaining_bytes], buf[len .. len + remaining_bytes]);
}
continue; // this switch block does not return a `Key` we continue with loop
},
};
this.postEvent(.{ .key = key });
} else {
var len = read_bytes;
while (!std.unicode.utf8ValidateSlice(buf[0..len])) len -= 1;
remaining_bytes = read_bytes - len;
try lines.appendSlice(this.gpa, buf[0..len]);
if (remaining_bytes > 0) {
@memmove(buf[0..remaining_bytes], buf[len .. len + remaining_bytes]);
} else {
if (read_bytes != 512 and buf[len - 1] == '\n') this.postEvent(.{ .line = try lines.toOwnedSlice(this.gpa) });
// NOTE line did not end with `\n` but with EOF, meaning the user canceled
if (read_bytes != 512 and buf[len - 1] != '\n') {
lines.clearRetainingCapacity();
this.postEvent(.cancel);
}
}
}
}
continue;
};
break;
}
}
pub fn panic_handler(msg: []const u8, _: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
terminal.disableMouseSupport() catch {};
terminal.showCursor() catch {};
terminal.resetCursor() catch {};
terminal.restoreScreen() catch {};
terminal.disableRawMode(&.{
.iflag = .{},
.lflag = .{},
.cflag = .{},
.oflag = .{},
.cc = undefined,
.line = 0,
.ispeed = undefined,
.ospeed = undefined,
}) catch {};
terminal.exitAltScreen() catch {};
std.debug.defaultPanic(msg, ret_addr);
}
const element = @import("element.zig");
pub const Model = M;
pub const Event = mergeTaggedUnions(event.SystemEvent, E);
pub const Container = @import("container.zig").Container(Model, Event);
pub const Element = element.Element(Model, Event);
pub const Alignment = element.Alignment(Model, Event);
pub const Button = element.Button(Model, Event, Queue);
pub const TextField = element.TextField(Model, Event);
pub const Input = element.Input(Model, Event, Queue);
pub const Progress = element.Progress(Model, Event, Queue);
pub const RadioButton = element.RadioButton(Model, Event);
pub const Scrollable = element.Scrollable(Model, Event);
pub const Selection = element.Selection(Model, Event);
pub const Queue = queue.Queue(Event, 512);
};
}
const log = std.log.scoped(.app);
const std = @import("std");
const mem = std.mem;
const fmt = std.fmt;
const posix = std.posix;
const Thread = std.Thread;
const Allocator = mem.Allocator;
const assert = std.debug.assert;
const event = @import("event.zig");
const input = @import("input.zig");
const terminal = @import("terminal.zig");
const queue = @import("queue.zig");
const mergeTaggedUnions = event.mergeTaggedUnions;
const isTaggedUnion = event.isTaggedUnion;
const isStruct = event.isStruct;
const Mouse = input.Mouse;
const Key = input.Key;
const Point = @import("point.zig").Point;

View File

@@ -1,21 +1,61 @@
const std = @import("std");
const Style = @import("style.zig");
//! Cell type containing content and formatting for each character in the terminal screen.
pub const Cell = @This();
style: Style = .{ .attributes = &.{} },
// TODO: embrace `zg` dependency more due to utf-8 encoding
cp: u21 = ' ',
style: Style = .{ .emphasis = &.{} },
pub fn eql(this: Cell, other: Cell) bool {
return this.cp == other.cp and this.style.eql(other.style);
}
pub fn reset(this: *Cell) void {
this.style = .{ .attributes = &.{} };
this.style = .{ .emphasis = &.{} };
this.cp = ' ';
}
pub fn value(this: Cell, writer: anytype) !void {
pub fn value(this: Cell, writer: *std.Io.Writer) !void {
try this.style.value(writer, this.cp);
}
const std = @import("std");
const Style = @import("style.zig");
const Cell = @This();
test "ascii styled text" {
const cells: [4]Cell = .{
.{ .cp = 'Y', .style = .{ .fg = .green, .bg = .grey, .emphasis = &.{} } },
.{ .cp = 'v', .style = .{ .emphasis = &.{ .bold, .underline } } },
.{ .cp = 'e', .style = .{ .emphasis = &.{.italic} } },
.{ .cp = 's', .style = .{ .fg = .lightgreen, .bg = .black, .emphasis = &.{.underline} } },
};
var writer = std.Io.Writer.Allocating.init(std.testing.allocator);
defer writer.deinit();
for (cells) |cell| {
try cell.value(&writer.writer);
}
try std.testing.expectEqualSlices(
u8,
"\x1b[38;5;10;48;5;8;59mY\x1b[0m\x1b[39;49;59;1;4mv\x1b[0m\x1b[39;49;59;3me\x1b[0m\x1b[38;5;2;48;5;16;59;4ms\x1b[0m",
writer.writer.buffer[0..writer.writer.end],
);
}
test "utf-8 styled text" {
const cells: [4]Cell = .{
.{ .cp = '╭', .style = .{ .fg = .green, .bg = .grey, .emphasis = &.{} } },
.{ .cp = '─', .style = .{ .emphasis = &.{} } },
.{ .cp = '┄', .style = .{ .emphasis = &.{} } },
.{ .cp = '┘', .style = .{ .fg = .lightgreen, .bg = .black, .emphasis = &.{.underline} } },
};
var writer = std.Io.Writer.Allocating.init(std.testing.allocator);
defer writer.deinit();
for (cells) |cell| {
try cell.value(&writer.writer);
}
try std.testing.expectEqualSlices(
u8,
"\x1b[38;5;10;48;5;8;59m╭\x1b[0m\x1b[39;49;59m─\x1b[0m\x1b[39;49;59m┄\x1b[0m\x1b[38;5;2;48;5;16;59;4m┘\x1b[0m",
writer.writer.buffer[0..writer.writer.end],
);
}

View File

@@ -1,15 +1,13 @@
const std = @import("std");
pub const Color = enum(u8) {
default = 0,
black = 16,
light_red = 1,
light_green,
light_yellow,
light_blue,
light_magenta,
light_cyan,
light_grey,
lightred = 1,
lightgreen,
lightyellow,
lightblue,
lightmagenta,
lightcyan,
lightgrey,
grey,
red,
green,
@@ -18,21 +16,23 @@ 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 {
pub inline fn write(this: Color, writer: *std.Io.Writer, comptime coloring: enum { fg, bg, ul }) !void {
if (this == .default) {
switch (coloring) {
.fg => try std.fmt.format(writer, "39", .{}),
.bg => try std.fmt.format(writer, "49", .{}),
.ul => try std.fmt.format(writer, "59", .{}),
.fg => try writer.printAscii("39", .{}),
.bg => try writer.printAscii("49", .{}),
.ul => try writer.printAscii("59", .{}),
}
} else {
switch (coloring) {
.fg => try std.fmt.format(writer, "38;5;{d}", .{@intFromEnum(this)}),
.bg => try std.fmt.format(writer, "48;5;{d}", .{@intFromEnum(this)}),
.ul => try std.fmt.format(writer, "58;5;{d}", .{@intFromEnum(this)}),
.fg => try writer.print("38;5;{d}", .{@intFromEnum(this)}),
.bg => try writer.print("48;5;{d}", .{@intFromEnum(this)}),
.ul => try writer.print("58;5;{d}", .{@intFromEnum(this)}),
}
}
}
};
const std = @import("std");

File diff suppressed because it is too large Load Diff

View File

@@ -50,6 +50,7 @@ pub const home = "\x1b[H";
pub const cup = "\x1b[{d};{d}H";
pub const hide_cursor = "\x1b[?25l";
pub const show_cursor = "\x1b[?25h";
pub const reset_cursor_shape = "\x1b[0 q";
pub const cursor_shape = "\x1b[{d} q";
pub const ri = "\x1bM";
pub const ind = "\n";
@@ -58,8 +59,11 @@ pub const cub = "\x1b[{d}D";
// Erase
pub const erase_below_cursor = "\x1b[J";
pub const clear_screen = "\x1b[2J";
// alt screen
pub const save_screen = "\x1b[?47h";
pub const restore_screen = "\x1b[?47l";
pub const smcup = "\x1b[?1049h";
pub const rmcup = "\x1b[?1049l";
@@ -89,7 +93,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";
@@ -136,5 +140,6 @@ pub const osc10_reset = "\x1b]110\x1b\\"; // reset fg to terminal default
pub const osc11_query = "\x1b]11;?\x1b\\"; // bg
pub const osc11_set = "\x1b]11;rgb:{x:0>2}{x:0>2}/{x:0>2}{x:0>2}/{x:0>2}{x:0>2}\x1b\\"; // set default terminal bg
pub const osc11_reset = "\x1b]111\x1b\\"; // reset bg to terminal default
pub const osc12_set = "\x1b]12;{s}\x1b\\"; // set the cursor color through the name of the 8 base colors!
pub const osc12_query = "\x1b]12;?\x1b\\"; // cursor color
pub const osc12_reset = "\x1b]112\x1b\\"; // reset cursor to terminal default

File diff suppressed because it is too large Load Diff

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

@@ -1,37 +1,55 @@
//! Events which are defined by the library. They might be extended by user
//! events. See `App` for more details about user defined events.
const std = @import("std");
const terminal = @import("terminal.zig");
const Size = @import("size.zig").Size;
const Key = @import("key.zig");
/// 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,
/// Cancel event to signify that the user provided an EOF
///
/// Usually this event is only triggered by the system in *non raw mode*
/// renderings otherwise the corresponding `.key` event would be fired instead.
cancel,
/// Resize event to signify that the application should re-draw to resize
///
/// Usually no `Container` nor `Element` should act on that event, as it
/// only serves for event based loops to force a re-draw with a new `Event`.
resize,
/// Ring the terminal bell to notify the user. This `Event` is handled by
/// every `Container` and will not be passed through the container tree.
bell,
/// Error event to notify other containers about a recoverable error
err: struct {
/// actual error
err: anyerror,
/// 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 line event received in *non raw mode* (instead of individual `key` events)
///
/// This event contains the entire line until the ending newline character
/// (which is included in the payload of this event).
line: []const u8,
/// Input key event received from the user
key: Key,
/// Focus event for mouse interaction
/// TODO: this should instead be a union with a `Size` to derive which container / element the focus meant for
/// Mouse input event
mouse: Mouse,
/// Focus event indicating that the application has gained the focus of the user
focus: bool,
};
/// Merge the two provided `union(enum)` `A` and `B` to a tagged union containing all fields of both tagged unions in `comptime`.
/// Declarations are not supported for `comptime` created types, see https://github.com/ziglang/zig/issues/6709 for details.
pub fn mergeTaggedUnions(comptime A: type, comptime B: type) type {
if (!isTaggedUnion(A) or !isTaggedUnion(B)) {
@compileError("Both types for merging tagged unions need to be of type `union(enum)`.");
}
// TODO maybe it makes sense to have a nested tagged union type (i.e. system: union(enum) and event: union(enum))
// - allows re-definition of system / built-in events
// - clearly shows which events are system / built-in ones and which are user defined events
// - the memory footprint for the nesting is not really harmful
if (!isTaggedUnion(A) or !isTaggedUnion(B)) @compileError("Both types for merging tagged unions need to be of type `union(enum)`.");
const a_fields = @typeInfo(A).@"union".fields;
const a_fields_tag = @typeInfo(A).@"union".tag_type.?;
const a_enum_fields = @typeInfo(a_fields_tag).@"enum".fields;
@@ -56,11 +74,27 @@ pub fn mergeTaggedUnions(comptime A: type, comptime B: type) type {
i += 1;
}
const log2_i = @bitSizeOf(@TypeOf(i)) - @clz(i);
// NOTE declarations are not supported for `comptime` types: https://github.com/ziglang/zig/issues/6709
// -> will lead to a compilation error when constructing the tagged union
// at the end of this function in case at least one of the provided tagged
// unions to merge contains declarations (which in this case can only be the
// user provided one)
const a_enum_decls = @typeInfo(A).@"union".decls;
const b_enum_decls = @typeInfo(B).@"union".decls;
var decls: [a_enum_decls.len + b_enum_decls.len]std.builtin.Type.Declaration = undefined;
var j: usize = 0;
for (a_enum_decls) |decl| {
decls[j] = decl;
j += 1;
}
for (b_enum_decls) |decl| {
decls[j] = decl;
j += 1;
}
const EventType = @Type(.{ .int = .{
.signedness = .unsigned,
.bits = log2_i,
.bits = @bitSizeOf(@TypeOf(i)) - @clz(i),
} });
const Event = @Type(.{ .@"enum" = .{
@@ -78,15 +112,28 @@ pub fn mergeTaggedUnions(comptime A: type, comptime B: type) type {
} });
}
// Determine at `comptime` whether the provided type `E` is an `union(enum)`.
pub fn isTaggedUnion(comptime E: type) bool {
switch (@typeInfo(E)) {
.@"union" => |u| {
if (u.tag_type) |_| {} else {
return false;
}
/// Determine whether the provided type `T` is a tagged union: `union(enum)`.
pub fn isTaggedUnion(comptime T: type) bool {
switch (@typeInfo(T)) {
.@"union" => |u| if (u.tag_type) |_| {} else {
return false;
},
else => return false,
}
return true;
}
/// Determine whether the provided type `T` is a `struct`.
pub fn isStruct(comptime T: type) bool {
return switch (@typeInfo(T)) {
.@"struct" => true,
else => false,
};
}
const std = @import("std");
const input = @import("input.zig");
const terminal = @import("terminal.zig");
const Key = input.Key;
const Mouse = input.Mouse;
const Point = @import("point.zig").Point;

238
src/input.zig Normal file
View File

@@ -0,0 +1,238 @@
//! Input module for `zterm`. Contains structs to represent key events and mouse events.
pub const Mouse = packed struct {
x: u16,
y: u16,
button: Button,
kind: Kind,
pub const Button = enum(u8) {
left,
middle,
right,
none,
wheel_up = 64,
wheel_down = 65,
wheel_right = 66,
wheel_left = 67,
button_8 = 128,
button_9 = 129,
button_10 = 130,
button_11 = 131,
};
pub const Kind = enum(u2) {
press,
release,
motion,
drag,
};
pub fn eql(this: @This(), other: @This()) bool {
return meta.eql(this, other);
}
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;
}
};
pub const Key = packed struct {
cp: u21,
mod: Modifier = .{},
pub const Modifier = packed struct {
shift: bool = false,
alt: bool = false,
ctrl: bool = false,
};
/// Compare _this_ `Key` with an _other_ `Key`.
///
/// # Example
///
/// Configure `ctrl+c` to quit the application (done in main event loop of the application):
///
/// ```zig
/// switch (event) {
/// .quit => break,
/// .key => |key| if (key.eql(.{ .cp = 'c', .mod = .{ .ctrl = true } })) app.quit.set(),
/// else => {},
/// }
/// ```
pub fn eql(this: @This(), other: @This()) bool {
return meta.eql(this, other);
}
/// Determine if the `Key` is an unicode character that can be printed to
/// the screen. This means that the code point of the `Key` is an ascii
/// character between 32 - 255 (with the exception of 127 = Delete) and no
/// modifiers (alt and/or ctrl) are used.
///
/// # Example
///
/// Get user input's from the .key event from the application event loop:
///
/// ```zig
/// switch (event) {
/// .key => |key| if (key.isUnicode()) try this.input.append(key.cp),
/// else => {},
/// }
/// ```
pub fn isUnicode(this: @This()) bool {
return this.mod.alt == false and this.mod.ctrl == false and // no modifier keys
(this.cp >= 32 and this.cp <= 126 or // ascii printable characters (except for input.Delete)
this.cp >= 128 and this.cp <= 255) or // extended ascii codes
((this.cp >= 0x0080 and this.cp <= 0x07FF) or
(this.cp >= 0x0800 and this.cp <= 0xFFFF) or
(this.cp >= 0x100000 and this.cp <= 0x10FFFF)) and // allowed unicode character ranges (2 - 4 byte characters)
(this.cp < 57348 or this.cp > 57454); // no other predefined meanings (i.e. arrow keys, etc.)
}
/// Determine if the `Key` is an ascii character that can be printed to
/// the screen. This means that the code point of the `Key` is an ascii
/// character between 32 - 255 (with the exception of 127 = Delete) and no
/// modifiers (alt and/or ctrl) are used.
///
/// # Example
///
/// Get user input's from the .key event from the application event loop:
///
/// ```zig
/// switch (event) {
/// .key => |key| if (key.isAscii()) try this.input.append(key.cp),
/// else => {},
/// }
/// ```
pub fn isAscii(this: @This()) bool {
return this.mod.alt == false and this.mod.ctrl == false and // no modifier keys
(this.cp >= 32 and this.cp <= 126 or // ascii printable characters (except for input.Delete)
this.cp >= 128 and this.cp <= 255); // extended ascii codes
}
test "isAscii with ascii character" {
try testing.expectEqual(true, isAscii(.{ .cp = 'c' }));
try testing.expectEqual(false, isAscii(.{ .cp = 'c', .mod = .{ .ctrl = true } }));
try testing.expectEqual(false, isAscii(.{ .cp = 'c', .mod = .{ .alt = true } }));
try testing.expectEqual(false, isAscii(.{ .cp = 'c', .mod = .{ .alt = true, .ctrl = true } }));
}
test "isAscii with non-ascii character" {
try testing.expectEqual(false, isAscii(.{ .cp = Escape }));
try testing.expectEqual(false, isAscii(.{ .cp = Enter }));
try testing.expectEqual(false, isAscii(.{ .cp = Enter, .mod = .{ .alt = true } }));
}
test "isAscii with excluded input.Delete" {
try testing.expectEqual(false, isAscii(.{ .cp = Delete }));
try testing.expectEqual(false, isAscii(.{ .cp = Delete, .mod = .{ .alt = false, .ctrl = false } }));
}
};
// TODO: std.ascii has the escape codes too!
// codepoints for keys
pub const Tab: u21 = 0x09;
pub const Enter: u21 = 0x0D;
pub const Escape: u21 = 0x1B;
pub const Space: u21 = 0x20;
pub const Backspace: u21 = 0x7F;
// kitty key encodings (re-used here)
pub const Insert: u21 = 57348;
pub const Delete: u21 = 57349;
pub const Left: u21 = 57350;
pub const Right: u21 = 57351;
pub const Up: u21 = 57352;
pub const Down: u21 = 57353;
pub const PageUp: u21 = 57354;
pub const PageDown: u21 = 57355;
pub const Home: u21 = 57356;
pub const End: u21 = 57357;
pub const CapsLock: u21 = 57358;
pub const ScrollLock: u21 = 57359;
pub const NumLock: u21 = 57360;
pub const PrintScreen: u21 = 57361;
pub const Pause: u21 = 57362;
pub const Menu: u21 = 57363;
pub const F1: u21 = 57364;
pub const F2: u21 = 57365;
pub const F3: u21 = 57366;
pub const F4: u21 = 57367;
pub const F5: u21 = 57368;
pub const F6: u21 = 57369;
pub const F7: u21 = 57370;
pub const F8: u21 = 57371;
pub const F9: u21 = 57372;
pub const F10: u21 = 57373;
pub const F11: u21 = 57374;
pub const F12: u21 = 57375;
pub const F13: u21 = 57376;
pub const F14: u21 = 57377;
pub const F15: u21 = 57378;
pub const F16: u21 = 57379;
pub const F17: u21 = 57380;
pub const F18: u21 = 57381;
pub const F19: u21 = 57382;
pub const F20: u21 = 57383;
pub const Kp0: u21 = 57399;
pub const Kp1: u21 = 57400;
pub const Kp2: u21 = 57401;
pub const Kp3: u21 = 57402;
pub const Kp4: u21 = 57403;
pub const Kp5: u21 = 57404;
pub const Kp6: u21 = 57405;
pub const Kp7: u21 = 57406;
pub const Kp8: u21 = 57407;
pub const Kp9: u21 = 57408;
pub const KpDecimal: u21 = 57409;
pub const KpDivide: u21 = 57410;
pub const KpMultiply: u21 = 57411;
pub const KpSubtract: u21 = 57412;
pub const KpAdd: u21 = 57413;
pub const KpEnter: u21 = 57414;
pub const KpEqual: u21 = 57415;
pub const KpSeparator: u21 = 57416;
pub const KpLeft: u21 = 57417;
pub const KpRight: u21 = 57418;
pub const KpUp: u21 = 57419;
pub const KpDown: u21 = 57420;
pub const KpPageUp: u21 = 57421;
pub const KpPageDown: u21 = 57422;
pub const KpHome: u21 = 57423;
pub const KpEnd: u21 = 57424;
pub const KpInsert: u21 = 57425;
pub const KpDelete: u21 = 57426;
pub const KpBegin: u21 = 57427;
pub const MediaPlay: u21 = 57428;
pub const MediaPause: u21 = 57429;
pub const MediaPlayPause: u21 = 57430;
pub const MediaReverse: u21 = 57431;
pub const MediaStop: u21 = 57432;
pub const MediaFastForward: u21 = 57433;
pub const MediaRewind: u21 = 57434;
pub const MediaTrackNext: u21 = 57435;
pub const MediaTrackPrevious: u21 = 57436;
pub const MediaRecord: u21 = 57437;
pub const LowerVolume: u21 = 57438;
pub const RaiseVolume: u21 = 57439;
pub const MuteVolume: u21 = 57440;
pub const LeftShift: u21 = 57441;
pub const LeftControl: u21 = 57442;
pub const LeftAlt: u21 = 57443;
pub const LeftSuper: u21 = 57444;
pub const LeftHyper: u21 = 57445;
pub const LeftMeta: u21 = 57446;
pub const RightShift: u21 = 57447;
pub const RightControl: u21 = 57448;
pub const RightAlt: u21 = 57449;
pub const RightSuper: u21 = 57450;
pub const RightHyper: u21 = 57451;
pub const RightMeta: u21 = 57452;
pub const IsoLevel3Shift: u21 = 57453;
pub const IsoLevel5Shift: u21 = 57454;
const std = @import("std");
const meta = std.meta;
const Point = @import("point.zig").Point;
const testing = std.testing;

View File

@@ -1,151 +0,0 @@
//! Keybindings and Modifiers for user input detection and selection.
const std = @import("std");
pub const Key = @This();
pub const Modifier = struct {
shift: bool = false,
alt: bool = false,
ctrl: bool = false,
};
cp: u21,
mod: Modifier = .{},
/// Compare _this_ `Key` with an _other_ `Key`.
///
/// # Example
///
/// Configure `ctrl+c` to quit the application (done in main event loop of the application):
///
/// ```zig
/// switch (event) {
/// .quit => break,
/// .key => |key| {
/// // ctrl+c to quit
/// if (terminal.Key.matches(key, .{ .cp = 'c', .mod = .{ .ctrl = true } })) {
/// app.quit.set();
/// }
/// },
/// else => {},
/// }
/// ```
pub fn matches(this: @This(), other: @This()) bool {
return std.meta.eql(this, other);
}
// codepoints for keys
pub const tab: u21 = 0x09;
pub const enter: u21 = 0x0D;
pub const escape: u21 = 0x1B;
pub const space: u21 = 0x20;
pub const backspace: u21 = 0x7F;
// kitty key encodings (re-used here)
pub const insert: u21 = 57348;
pub const delete: u21 = 57349;
pub const left: u21 = 57350;
pub const right: u21 = 57351;
pub const up: u21 = 57352;
pub const down: u21 = 57353;
pub const page_up: u21 = 57354;
pub const page_down: u21 = 57355;
pub const home: u21 = 57356;
pub const end: u21 = 57357;
pub const caps_lock: u21 = 57358;
pub const scroll_lock: u21 = 57359;
pub const num_lock: u21 = 57360;
pub const print_screen: u21 = 57361;
pub const pause: u21 = 57362;
pub const menu: u21 = 57363;
pub const f1: u21 = 57364;
pub const f2: u21 = 57365;
pub const f3: u21 = 57366;
pub const f4: u21 = 57367;
pub const f5: u21 = 57368;
pub const f6: u21 = 57369;
pub const f7: u21 = 57370;
pub const f8: u21 = 57371;
pub const f9: u21 = 57372;
pub const f10: u21 = 57373;
pub const f11: u21 = 57374;
pub const f12: u21 = 57375;
pub const f13: u21 = 57376;
pub const f14: u21 = 57377;
pub const f15: u21 = 57378;
pub const @"f16": u21 = 57379;
pub const f17: u21 = 57380;
pub const f18: u21 = 57381;
pub const f19: u21 = 57382;
pub const f20: u21 = 57383;
pub const f21: u21 = 57384;
pub const f22: u21 = 57385;
pub const f23: u21 = 57386;
pub const f24: u21 = 57387;
pub const f25: u21 = 57388;
pub const f26: u21 = 57389;
pub const f27: u21 = 57390;
pub const f28: u21 = 57391;
pub const f29: u21 = 57392;
pub const f30: u21 = 57393;
pub const f31: u21 = 57394;
pub const @"f32": u21 = 57395;
pub const f33: u21 = 57396;
pub const f34: u21 = 57397;
pub const f35: u21 = 57398;
pub const kp_0: u21 = 57399;
pub const kp_1: u21 = 57400;
pub const kp_2: u21 = 57401;
pub const kp_3: u21 = 57402;
pub const kp_4: u21 = 57403;
pub const kp_5: u21 = 57404;
pub const kp_6: u21 = 57405;
pub const kp_7: u21 = 57406;
pub const kp_8: u21 = 57407;
pub const kp_9: u21 = 57408;
pub const kp_decimal: u21 = 57409;
pub const kp_divide: u21 = 57410;
pub const kp_multiply: u21 = 57411;
pub const kp_subtract: u21 = 57412;
pub const kp_add: u21 = 57413;
pub const kp_enter: u21 = 57414;
pub const kp_equal: u21 = 57415;
pub const kp_separator: u21 = 57416;
pub const kp_left: u21 = 57417;
pub const kp_right: u21 = 57418;
pub const kp_up: u21 = 57419;
pub const kp_down: u21 = 57420;
pub const kp_page_up: u21 = 57421;
pub const kp_page_down: u21 = 57422;
pub const kp_home: u21 = 57423;
pub const kp_end: u21 = 57424;
pub const kp_insert: u21 = 57425;
pub const kp_delete: u21 = 57426;
pub const kp_begin: u21 = 57427;
pub const media_play: u21 = 57428;
pub const media_pause: u21 = 57429;
pub const media_play_pause: u21 = 57430;
pub const media_reverse: u21 = 57431;
pub const media_stop: u21 = 57432;
pub const media_fast_forward: u21 = 57433;
pub const media_rewind: u21 = 57434;
pub const media_track_next: u21 = 57435;
pub const media_track_previous: u21 = 57436;
pub const media_record: u21 = 57437;
pub const lower_volume: u21 = 57438;
pub const raise_volume: u21 = 57439;
pub const mute_volume: u21 = 57440;
pub const left_shift: u21 = 57441;
pub const left_control: u21 = 57442;
pub const left_alt: u21 = 57443;
pub const left_super: u21 = 57444;
pub const left_hyper: u21 = 57445;
pub const left_meta: u21 = 57446;
pub const right_shift: u21 = 57447;
pub const right_control: u21 = 57448;
pub const right_alt: u21 = 57449;
pub const right_super: u21 = 57450;
pub const right_hyper: u21 = 57451;
pub const right_meta: u21 = 57452;
pub const iso_level_3_shift: u21 = 57453;
pub const iso_level_5_shift: u21 = 57454;

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

View File

@@ -1,9 +1,7 @@
// taken from https://github.com/rockorager/libvaxis/blob/main/src/queue.zig (MIT-License)
// with slight modifications
const std = @import("std");
const assert = std.debug.assert;
/// Thread safe. Fixed size. Blocking push and pop.
/// Queue implementation. Thread safe. Fixed size. _Blocking_ `push` and `pop`. _Polling_ through `tryPop` and `tryPush`.
pub fn Queue(comptime T: type, comptime size: usize) type {
return struct {
buf: [size]T = undefined,
@@ -92,6 +90,23 @@ pub fn Queue(comptime T: type, comptime size: usize) type {
assert(!this.isEmptyLH());
}
pub fn lock(this: *QueueType) void {
this.mutex.lock();
}
pub fn unlock(this: *QueueType) void {
this.mutex.unlock();
}
/// Used to efficiently drain the queue
pub fn drain(this: *QueueType) ?T {
if (this.isEmptyLH()) return null;
const result = this.buf[this.mask(this.read_index)];
this.read_index = this.mask2(this.read_index + 1);
return result;
}
fn isEmptyLH(this: QueueType) bool {
return this.write_index == this.read_index;
}
@@ -116,7 +131,7 @@ pub fn Queue(comptime T: type, comptime size: usize) type {
}
/// Returns the length
fn len(this: QueueType) usize {
pub fn len(this: QueueType) usize {
const wrap_offset = 2 * this.buf.len *
@intFromBool(this.write_index < this.read_index);
const adjusted_write_index = this.write_index + wrap_offset;
@@ -135,8 +150,12 @@ pub fn Queue(comptime T: type, comptime size: usize) type {
};
}
const std = @import("std");
const testing = std.testing;
const assert = std.debug.assert;
const Thread = std.Thread;
const cfg = Thread.SpawnConfig{ .allocator = testing.allocator };
test "Queue: simple push / pop" {
var queue: Queue(u8, 16) = .{};
queue.push(1);
@@ -146,7 +165,6 @@ test "Queue: simple push / pop" {
try testing.expectEqual(2, queue.pop());
}
const Thread = std.Thread;
fn testPushPop(q: *Queue(u8, 2)) !void {
q.push(3);
try testing.expectEqual(2, q.pop());
@@ -197,9 +215,9 @@ fn sleepyPop(q: *Queue(u8, 2)) !void {
// still full and the push in the other thread is still blocked
// waiting for space.
try Thread.yield();
std.time.sleep(std.time.ns_per_s);
std.Thread.sleep(std.time.ns_per_s);
// Finally, let that other thread go.
try std.testing.expectEqual(1, q.pop());
try testing.expectEqual(1, q.pop());
// This won't continue until the other thread has had a chance to
// put at least one item in the queue.
@@ -207,7 +225,7 @@ fn sleepyPop(q: *Queue(u8, 2)) !void {
try Thread.yield();
// But we want to ensure that there's a second push waiting, so
// here's another sleep.
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
// Another spurious wake...
q.not_full.signal();
@@ -215,10 +233,10 @@ fn sleepyPop(q: *Queue(u8, 2)) !void {
// And another chance for the other thread to see that it's
// spurious and go back to sleep.
try Thread.yield();
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
// Pop that thing and we're done.
try std.testing.expectEqual(2, q.pop());
try testing.expectEqual(2, q.pop());
}
test "Fill, block, fill, block" {
@@ -238,28 +256,28 @@ test "Fill, block, fill, block" {
// Just to make sure the sleeps are yielding to this thread, make
// sure it took at least 900ms to do the push.
try std.testing.expect(then - now > 900);
try testing.expect(then - now > 900);
// This should block again, waiting for the other thread.
queue.push(4);
// And once that push has gone through, the other thread's done.
thread.join();
try std.testing.expectEqual(3, queue.pop());
try std.testing.expectEqual(4, queue.pop());
try testing.expectEqual(3, queue.pop());
try testing.expectEqual(4, queue.pop());
}
fn sleepyPush(q: *Queue(u8, 1)) !void {
// Try to ensure the other thread has already started trying to pop.
try Thread.yield();
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
// Spurious wake
q.not_full.signal();
q.not_empty.signal();
try Thread.yield();
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
// Stick something in the queue so it can be popped.
q.push(1);
@@ -268,7 +286,7 @@ fn sleepyPush(q: *Queue(u8, 1)) !void {
try Thread.yield();
// Give the other thread time to block again.
try Thread.yield();
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
// Spurious wake
q.not_full.signal();
@@ -284,8 +302,8 @@ test "Drain, block, drain, block" {
var queue: Queue(u8, 1) = .{};
const thread = try Thread.spawn(cfg, sleepyPush, .{&queue});
try std.testing.expectEqual(1, queue.pop());
try std.testing.expectEqual(2, queue.pop());
try testing.expectEqual(1, queue.pop());
try testing.expectEqual(2, queue.pop());
thread.join();
}
@@ -299,7 +317,7 @@ test "2 readers" {
const t1 = try Thread.spawn(cfg, readerThread, .{&queue});
const t2 = try Thread.spawn(cfg, readerThread, .{&queue});
try Thread.yield();
std.time.sleep(std.time.ns_per_s / 2);
std.Thread.sleep(std.time.ns_per_s / 2);
queue.push(1);
queue.push(1);
t1.join();

View File

@@ -1,21 +1,14 @@
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;
//! Renderer for `zterm`.
/// Double-buffered intermediate rendering pipeline
pub const Buffered = struct {
const log = std.log.scoped(.renderer_buffered);
// _ = log;
allocator: std.mem.Allocator,
allocator: Allocator,
created: bool,
size: Size,
size: Point,
screen: []Cell,
virtual_screen: []Cell,
pub fn init(allocator: std.mem.Allocator) @This() {
pub fn init(allocator: Allocator) @This() {
return .{
.allocator = allocator,
.created = false,
@@ -32,84 +25,198 @@ pub const Buffered = struct {
}
}
pub fn resize(this: *@This(), size: Size) !void {
log.debug("renderer::resize", .{});
defer this.size = size;
pub fn resize(this: *@This()) !Point {
const size = terminal.getTerminalSize();
if (meta.eql(this.size, size)) return this.size;
this.size = size;
const n = @as(usize, this.size.x) * @as(usize, this.size.y);
if (!this.created) {
this.screen = this.allocator.alloc(Cell, @as(usize, size.cols) * @as(usize, size.rows)) catch @panic("render.zig: Out of memory.");
@memset(this.screen, .{});
this.virtual_screen = this.allocator.alloc(Cell, @as(usize, size.cols) * @as(usize, size.rows)) catch @panic("render.zig: Out of memory.");
this.screen = this.allocator.alloc(Cell, n) catch @panic("render.zig: Out of memory.");
this.virtual_screen = this.allocator.alloc(Cell, n) catch @panic("render.zig: Out of memory.");
@memset(this.virtual_screen, .{});
this.created = true;
} else {
this.allocator.free(this.screen);
this.screen = this.allocator.alloc(Cell, @as(usize, size.cols) * @as(usize, size.rows)) catch @panic("render.zig: Out of memory.");
@memset(this.screen, .{});
this.screen = this.allocator.alloc(Cell, n) catch @panic("render.zig: Out of memory.");
this.allocator.free(this.virtual_screen);
this.virtual_screen = this.allocator.alloc(Cell, @as(usize, size.cols) * @as(usize, size.rows)) catch @panic("render.zig: Out of memory.");
this.virtual_screen = this.allocator.alloc(Cell, n) catch @panic("render.zig: Out of memory.");
@memset(this.virtual_screen, .{});
}
try this.clear();
return size;
}
/// Clear the entire screen and reset the screen buffer, to force a re-draw with the next `flush` call.
pub fn clear(this: *@This()) !void {
log.debug("renderer::clear", .{});
try terminal.clearScreen();
@memset(this.screen, .{});
}
/// Render provided cells at size (anchor and dimension) into the *virtual screen*.
pub fn render(this: *@This(), comptime T: type, container: *T) !void {
const viewport: Size = container.viewport;
const cells: []const Cell = try container.contents();
pub fn render(this: *@This(), comptime Container: type, container: *Container, comptime Model: type, model: *const Model) !void {
const size: Point = container.size;
const origin: Point = container.origin;
const cells: []const Cell = try container.content(model);
if (cells.len == 0) return;
var idx: usize = 0;
var vs = this.virtual_screen;
const anchor: usize = (@as(usize, viewport.anchor.row) * @as(usize, this.size.cols)) + @as(usize, viewport.anchor.col);
const anchor: usize = (@as(usize, origin.y) * @as(usize, this.size.x)) + @as(usize, origin.x);
blk: for (0..viewport.rows) |row| {
for (0..viewport.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;
}
}
// free immediately
container.allocator.free(cells);
for (container.elements.items) |*element| {
try this.render(T, element);
}
for (container.elements.items) |*element| try this.render(Container, element, Model, model);
}
/// 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?
log.debug("renderer::flush", .{});
const writer = terminal.writer();
try terminal.hideCursor();
// TODO measure timings of rendered frames?
var cursor_position: ?Point = null;
var 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];
// update the latest found cursor position
if (cvs.style.cursor) {
assert(cursor_position == null);
cursor_position = .{
.x = @truncate(col),
.y = @truncate(row),
};
try cvs.style.set_cursor_style(&writer);
}
if (cs.eql(cvs)) continue;
// render differences found in virtual screen
try terminal.setCursorPosition(.{ .row = @truncate(row + 1), .col = @truncate(col + 1) });
try cvs.value(writer);
try terminal.setCursorPosition(.{ .y = @truncate(row), .x = @truncate(col) });
try cvs.value(&writer);
// update screen to be the virtual screen for the next frame
s[idx] = vs[idx];
}
}
if (cursor_position) |point| {
try terminal.showCursor();
try terminal.setCursorPosition(point);
}
}
};
pub const Direct = struct {
gpa: Allocator,
size: Point,
resized: bool,
screen: []Cell,
pub fn init(gpa: Allocator) @This() {
return .{
.gpa = gpa,
.size = .{},
.resized = true,
.screen = undefined,
};
}
pub fn deinit(this: *@This()) void {
this.gpa.free(this.screen);
}
pub fn resize(this: *@This()) !Point {
this.size = .{};
if (!this.resized) {
this.gpa.free(this.screen);
this.screen = undefined;
}
this.resized = true;
return terminal.getTerminalSize();
}
pub fn clear(this: *@This()) !void {
_ = this;
try terminal.clearScreen();
}
pub fn writeCtrlDWithNewline(this: *@This()) !void {
_ = this;
_ = try terminal.write("^D\n");
}
pub fn writeNewline(this: *@This()) !void {
_ = this;
_ = try terminal.write("\n");
}
/// Render provided cells at size (anchor and dimension) into the *screen*.
pub fn render(this: *@This(), comptime Container: type, container: *Container, comptime Model: type, model: *const Model) !void {
const size: Point = container.size;
const origin: Point = container.origin;
if (this.resized) {
this.size = size;
const n = @as(usize, this.size.x) * @as(usize, this.size.y);
this.screen = try this.gpa.alloc(Cell, n);
@memset(this.screen, .{});
this.resized = false;
}
const cells: []const Cell = try container.content(model);
var idx: usize = 0;
var vs = this.screen;
const anchor: usize = (@as(usize, origin.y) * @as(usize, this.size.x)) + @as(usize, origin.x);
blk: for (0..size.y) |row| {
for (0..size.x) |col| {
vs[anchor + (row * this.size.x) + col] = cells[idx];
idx += 1;
if (cells.len == idx) break :blk;
}
}
// free immediately
container.allocator.free(cells);
for (container.elements.items) |*element| try this.render(Container, element, Model, model);
}
pub fn flush(this: *@This()) !void {
var writer = terminal.writer();
for (0..this.size.y) |row| {
for (0..this.size.x) |col| {
const idx = (row * this.size.x) + col;
const cvs = this.screen[idx];
try cvs.value(&writer);
if (cvs.style.cursor) return; // that's where the cursor should be left!
}
}
}
};
const std = @import("std");
const meta = std.meta;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminal = @import("terminal.zig");
const Cell = @import("cell.zig");
const Point = @import("point.zig").Point;

View File

@@ -1,30 +1,39 @@
// 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`
pub const Renderer = @import("render.zig");
// Container Configurations
pub const Border = container.Border;
pub const Rectangle = container.Rectangle;
pub const Scroll = container.Scroll;
pub const Layout = container.Layout;
pub const Cell = @import("cell.zig");
pub const Color = color.Color;
pub const Key = @import("key.zig");
pub const Size = size.Size;
pub const Key = input.Key;
pub const Mouse = input.Mouse;
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;

View File

@@ -1,10 +0,0 @@
pub const Size = packed struct {
anchor: Position = .{},
cols: u16 = 0,
rows: u16 = 0,
};
pub const Position = packed struct {
col: u16 = 0,
row: u16 = 0,
};

View File

@@ -7,11 +7,15 @@
// taken from https://github.com/rockorager/libvaxis/blob/main/src/Cell.zig (MIT-License)
// with slight modifications
const std = @import("std");
const Color = @import("color.zig").Color;
pub const Style = @This();
fg: Color = .default,
bg: Color = .default,
ul: Color = .default,
cursor: bool = false,
cursor_color: Color = .default,
cursor_shape: CursorShape = .default,
ul_style: Underline = .off,
emphasis: []const Emphasis,
pub const Underline = enum {
off,
@@ -22,7 +26,7 @@ pub const Underline = enum {
dashed,
};
pub const Attribute = enum(u8) {
pub const Emphasis = enum(u8) {
reset = 0,
bold = 1,
dim,
@@ -34,40 +38,61 @@ pub const Attribute = enum(u8) {
strikethrough,
};
fg: Color = .white,
bg: Color = .default,
ul: Color = .default,
ul_style: Underline = .off,
attributes: []const Attribute,
pub const CursorShape = enum(u4) {
default = 0,
block_blinking = 1,
block_steady,
underline_blinking,
underline_steady,
bar_blinking,
bar_steady,
};
pub fn eql(this: Style, other: Style) bool {
return std.meta.eql(this, other);
// TODO should there be a compare for every field?
return meta.eql(this, other);
}
pub fn value(this: Style, writer: anytype, cp: u21) !void {
pub fn set_cursor_style(this: Style, writer: *std.Io.Writer) !void {
if (!this.cursor) return;
switch (this.cursor_color) {
.default => try writer.print(ctlseqs.osc12_reset, .{}),
else => try writer.print(ctlseqs.osc12_set, .{@tagName(this.cursor_color)}),
}
try writer.print(ctlseqs.cursor_shape, .{@intFromEnum(this.cursor_shape)});
}
pub fn value(this: Style, writer: *std.Io.Writer, cp: u21) !void {
var buffer: [4]u8 = undefined;
const bytes = try std.unicode.utf8Encode(cp, &buffer);
std.debug.assert(bytes > 0);
const bytes = try unicode.utf8Encode(cp, &buffer);
assert(bytes > 0);
// build ansi sequence for 256 colors ...
// foreground
try std.fmt.format(writer, "\x1b[", .{});
try writer.printAscii("\x1b[", .{});
try this.fg.write(writer, .fg);
// background
try std.fmt.format(writer, ";", .{});
try writer.printAsciiChar(';', .{});
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
try std.fmt.format(writer, ";", .{});
// FIX assert that if the underline property is set that the ul style and the attribute for underlining is available
try writer.printAsciiChar(';', .{});
try this.ul.write(writer, .ul);
// append styles (aka attributes like bold, italic, strikethrough, etc.)
for (this.attributes) |attribute| {
try std.fmt.format(writer, ";{d}", .{@intFromEnum(attribute)});
}
try std.fmt.format(writer, "m", .{});
for (this.emphasis) |attribute| try writer.print(";{d}", .{@intFromEnum(attribute)});
try writer.printAsciiChar('m', .{});
// content
try std.fmt.format(writer, "{s}", .{buffer});
try writer.printAscii(buffer[0..bytes], .{});
try writer.printAscii("\x1b[0m", .{});
}
// TODO: implement helper functions for terminal capabilities:
// TODO implement helper functions for terminal capabilities:
// - links / url display (osc 8)
// - show / hide cursor?
const std = @import("std");
const unicode = std.unicode;
const meta = std.meta;
const assert = std.debug.assert;
const Color = @import("color.zig").Color;
const ctlseqs = @import("ctlseqs.zig");
const Style = @This();

View File

@@ -1,13 +1,3 @@
const std = @import("std");
pub const code_point = @import("code_point");
const Key = @import("key.zig");
const Position = @import("size.zig").Position;
const Size = @import("size.zig").Size;
const Cell = @import("cell.zig");
const log = std.log.scoped(.terminal);
// Ref: https://vt100.net/docs/vt510-rm/DECRPM.html
pub const ReportMode = enum {
not_recognized,
@@ -19,81 +9,104 @@ pub const ReportMode = enum {
/// Gets number of rows and columns in the terminal
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 };
var ws: posix.winsize = undefined;
_ = posix.system.ioctl(posix.STDIN_FILENO, posix.T.IOCGWINSZ, @intFromPtr(&ws));
return .{ .x = ws.col, .y = ws.row };
}
pub fn saveScreen() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?47h");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.save_screen);
}
pub fn restoreScreen() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?47l");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.restore_screen);
}
pub fn enterAltScreen() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?1049h");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.smcup);
}
pub fn exitAltScreen() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?1049l");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.rmcup);
}
pub fn clearScreen() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[2J");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.clear_screen);
}
pub fn hideCursor() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?25l");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.hide_cursor);
}
pub fn showCursor() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?25h");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.show_cursor);
}
pub fn resetCursor() !void {
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.reset_cursor_shape);
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.osc12_reset);
}
pub fn setCursorPositionHome() !void {
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[H");
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.home);
}
pub fn enableMouseSupport() !void {
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.mouse_set);
}
pub fn disableMouseSupport() !void {
_ = try posix.write(posix.STDIN_FILENO, ctlseqs.mouse_reset);
}
pub fn ringBell() !void {
_ = try posix.write(posix.STDIN_FILENO, &.{7});
}
pub fn read(buf: []u8) !usize {
return try std.posix.read(std.posix.STDIN_FILENO, buf);
return try posix.read(posix.STDIN_FILENO, buf);
}
pub fn write(buf: []const u8) !usize {
return try std.posix.write(std.posix.STDIN_FILENO, buf);
return try posix.write(posix.STDIN_FILENO, buf);
}
fn contextWrite(context: @This(), data: []const u8) anyerror!usize {
_ = context;
return try std.posix.write(std.posix.STDOUT_FILENO, data);
fn drainFn(w: *std.Io.Writer, data: []const []const u8, splat: usize) error{WriteFailed}!usize {
_ = w;
if (data.len == 0 or splat == 0) return 0;
var len: usize = 0;
for (data) |bytes| len += posix.write(posix.STDOUT_FILENO, bytes) catch return error.WriteFailed;
return len;
}
const Writer = std.io.Writer(
@This(),
anyerror,
contextWrite,
);
pub fn writer() Writer {
return .{ .context = .{} };
// TODO I now need to add that much, for just the one function above?
pub fn writer() std.Io.Writer {
return .{
.vtable = &.{
.drain = drainFn,
.flush = std.Io.Writer.noopFlush,
},
.buffer = &.{},
};
}
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 });
_ = try std.posix.write(std.posix.STDIN_FILENO, value);
const value = try std.fmt.bufPrint(&buf, "\x1b[{d};{d}H", .{ pos.y + 1, pos.x + 1 });
_ = try posix.write(posix.STDIN_FILENO, value);
}
pub fn getCursorPosition() !Size.Position {
pub fn getCursorPosition() !Size {
// Needs Raw mode (no wait for \n) to work properly cause
// control sequence will not be written without it.
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[6n");
_ = try posix.write(posix.STDIN_FILENO, "\x1b[6n");
var buf: [64]u8 = undefined;
// format: \x1b, "[", R1,..., Rn, ";", C1, ..., Cn, "R"
const len = try std.posix.read(std.posix.STDIN_FILENO, &buf);
const len = try posix.read(posix.STDIN_FILENO, &buf);
if (!isCursorPosition(buf[0..len])) {
return error.InvalidValueReturned;
@@ -127,8 +140,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,
};
}
@@ -156,8 +169,8 @@ pub fn isCursorPosition(buf: []u8) bool {
///
/// `bak`: pointer to store termios struct backup before
/// altering, this is used to disable raw mode.
pub fn enableRawMode(bak: *std.posix.termios) !void {
var termios = try std.posix.tcgetattr(std.posix.STDIN_FILENO);
pub fn enableRawMode(bak: *posix.termios) !void {
var termios = try posix.tcgetattr(posix.STDIN_FILENO);
bak.* = termios;
// termios flags used by termios(3)
@@ -182,20 +195,20 @@ pub fn enableRawMode(bak: *std.posix.termios) !void {
termios.cflag.CSIZE = .CS8;
termios.cflag.PARENB = false;
termios.cc[@intFromEnum(std.posix.V.MIN)] = 1;
termios.cc[@intFromEnum(std.posix.V.TIME)] = 0;
termios.cc[@intFromEnum(posix.V.MIN)] = 1;
termios.cc[@intFromEnum(posix.V.TIME)] = 0;
try std.posix.tcsetattr(
std.posix.STDIN_FILENO,
try posix.tcsetattr(
posix.STDIN_FILENO,
.FLUSH,
termios,
);
}
/// Reverts `enableRawMode` to restore initial functionality.
pub fn disableRawMode(bak: *std.posix.termios) !void {
try std.posix.tcsetattr(
std.posix.STDIN_FILENO,
pub fn disableRawMode(bak: *const posix.termios) !void {
try posix.tcsetattr(
posix.STDIN_FILENO,
.FLUSH,
bak.*,
);
@@ -205,13 +218,13 @@ pub fn disableRawMode(bak: *std.posix.termios) !void {
pub fn canSynchornizeOutput() !bool {
// Needs Raw mode (no wait for \n) to work properly cause
// control sequence will not be written without it.
_ = try std.posix.write(std.posix.STDIN_FILENO, "\x1b[?2026$p");
_ = try posix.write(posix.STDIN_FILENO, "\x1b[?2026$p");
var buf: [64]u8 = undefined;
// format: \x1b, "[", "?", "2", "0", "2", "6", ";", n, "$", "y"
const len = try std.posix.read(std.posix.STDIN_FILENO, &buf);
if (!std.mem.eql(u8, buf[0..len], "\x1b[?2026;") or len < 9) {
const len = try posix.read(posix.STDIN_FILENO, &buf);
if (!mem.eql(u8, buf[0..len], "\x1b[?2026;") or len < 9) {
return false;
}
@@ -228,3 +241,16 @@ fn getReportMode(ps: u8) ReportMode {
else => ReportMode.not_recognized,
};
}
const log = std.log.scoped(.terminal);
const std = @import("std");
const mem = std.mem;
const posix = std.posix;
const assert = std.debug.assert;
const ctlseqs = @import("ctlseqs.zig");
const input = @import("input.zig");
const Key = input.Key;
const Point = @import("point.zig").Point;
const Size = @import("point.zig").Point;
const Cell = @import("cell.zig");

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

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

234
src/testing.zig Normal file
View File

@@ -0,0 +1,234 @@
//! Testing namespace for `zterm` to provide testing capabilities for `Containers`, `Event` handling, `App`s and `Element` implementations.
/// Single-buffer test rendering pipeline for testing purposes.
pub const Renderer = struct {
allocator: Allocator,
size: Point,
screen: []Cell,
pub fn init(allocator: 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 .{
.allocator = allocator,
.size = size,
.screen = screen,
};
}
pub fn deinit(this: *@This()) void {
this.allocator.free(this.screen);
}
pub fn resize(this: *@This(), size: Point) !void {
this.size = size;
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.");
@memset(this.screen, .{});
}
pub fn clear(this: *@This()) !void {
@memset(this.screen, .{});
}
pub fn render(this: *@This(), comptime T: type, container: *const T, comptime Model: type, model: *const Model) !void {
const size: Point = container.size;
const origin: Point = container.origin;
const cells: []const Cell = try container.content(model);
if (cells.len == 0) return;
var idx: usize = 0;
const anchor = (@as(usize, origin.y) * @as(usize, this.size.x)) + @as(usize, origin.x);
blk: for (0..size.y) |row| {
for (0..size.x) |col| {
const cell = cells[idx];
idx += 1;
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;
}
}
// free immediately
container.allocator.free(cells);
for (container.elements.items) |*element| try this.render(T, element, Model, model);
}
pub fn save(this: @This(), writer: anytype) !void {
try std.zon.stringify.serialize(this.screen, .{ .whitespace = false }, writer);
}
};
/// This function is intended to be used only in tests. Test if a `Container`'s
/// rendered contents are equal to the expected `Cell` slice.
///
/// # Test data creation
///
/// Create a .zon file containing the expected `Cell` slice using the `zterm.testing.Renderer.save` method:
///
/// ```zig
/// const Model = struct {};
/// var model: Model = .{};
/// const file = try std.fs.cwd().createFile("test/container/border/all.zon", .{ .truncate = true });
/// defer file.close();
///
/// const allocator = std.testing.allocator;
/// var renderer: testing.Renderer = .init(allocator, size);
/// defer renderer.deinit();
///
/// try container.handle(&model, .{ .size = size });
/// try renderer.render(@TypeOf(container), &container, Model, &.{});
/// try renderer.save(file.writer());
/// ```
///
/// # Testing against created data
///
/// Then later load that .zon file at compile time and run your test against this `Cell` slice.
///
/// ```zig
/// const Model = struct {};
/// var container: Container(Model, event.SystemEvent) = try .init(std.testing.allocator, .{
/// .border = .{
/// .color = .green,
/// .sides = .all,
/// },
/// }, .{});
/// defer container.deinit();
///
/// try testing.expectContainerScreen(.{
/// .rows = 20,
/// .cols = 30,
/// }, @TypeOf(container), &container, Model, @import("test/container/border.all.zon"));
/// ```
pub fn expectContainerScreen(size: Point, comptime T: type, container: *T, comptime Model: type, expected: []const Cell) !void {
const allocator = testing.allocator;
var renderer: Renderer = .init(allocator, size);
defer renderer.deinit();
const model: Model = .{};
container.resize(&model, size);
container.reposition(&model, .{});
try renderer.render(T, container, Model, &model);
try expectEqualCells(.{}, renderer.size, expected, renderer.screen);
}
/// Taken from: https://codeberg.org/atman/zg/src/branch/master/src/DisplayWidth.zig
/// Owned by https://codeberg.org/atman licensed under MIT all credits for this function go to him
fn center(allocator: Allocator, str: []const u8, total_width: usize, pad: []const u8) ![]u8 {
if (str.len > total_width) return error.StrTooLong;
if (str.len == total_width) return try allocator.dupe(u8, str);
if (pad.len > total_width or str.len + pad.len > total_width) return error.PadTooLong;
const margin_width = @divFloor((total_width - str.len), 2);
if (pad.len > margin_width) return error.PadTooLong;
const extra_pad: usize = if (total_width % 2 != str.len % 2) 1 else 0;
const pads = @divFloor(margin_width, pad.len) * 2 + extra_pad;
var result = try allocator.alloc(u8, pads * pad.len + str.len);
var bytes_index: usize = 0;
var pads_index: usize = 0;
while (pads_index < pads / 2) : (pads_index += 1) {
@memcpy(result[bytes_index..][0..pad.len], pad);
bytes_index += pad.len;
}
@memcpy(result[bytes_index..][0..str.len], str);
bytes_index += str.len;
pads_index = 0;
while (pads_index < pads / 2 + extra_pad) : (pads_index += 1) {
@memcpy(result[bytes_index..][0..pad.len], pad);
bytes_index += pad.len;
}
return result;
}
/// 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(origin: Point, size: Point, expected: []const Cell, actual: []const Cell) !void {
const allocator = testing.allocator;
try testing.expectEqual(expected.len, actual.len);
try testing.expectEqual(expected.len, @as(usize, size.y) * @as(usize, size.x));
var expected_cps = try std.ArrayList(Cell).initCapacity(allocator, size.x);
defer expected_cps.deinit(allocator);
var actual_cps = try std.ArrayList(Cell).initCapacity(allocator, size.x);
defer actual_cps.deinit(allocator);
var allocating_writer = std.Io.Writer.Allocating.init(allocator);
defer allocating_writer.deinit();
var writer = &allocating_writer.writer;
var differ = false;
const expected_centered = try center(allocator, "Expected Screen", size.x, " ");
defer allocator.free(expected_centered);
const actual_centered = try 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 });
for (origin.y..size.y) |row| {
defer {
expected_cps.clearRetainingCapacity();
actual_cps.clearRetainingCapacity();
}
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;
try expected_cps.append(allocator, expected_cell);
try actual_cps.append(allocator, actual_cell);
}
// write screens both formatted to buffer
for (expected_cps.items) |cell| try cell.value(writer);
_ = try writer.write("");
for (actual_cps.items) |cell| try cell.value(writer);
_ = try writer.write("\n");
}
if (!differ) return;
// test failed
var buf: [1024]u8 = undefined;
std.debug.lockStdErr();
defer std.debug.unlockStdErr();
var buffer = std.fs.File.stderr().writer(&buf);
var error_writer = &buffer.interface;
try error_writer.writeAll(writer.buffer[0..writer.end]);
try error_writer.flush();
return error.TestExpectEqualCells;
}
const std = @import("std");
const debug = std.debug;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const event = @import("event.zig");
const Container = @import("container.zig").Container;
const Cell = @import("cell.zig");
const Point = @import("point.zig").Point;