diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-25 21:41:59 -0600 |
|---|---|---|
| committer | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-25 21:41:59 -0600 |
| commit | c4ca679ab630d64f030f2529f6d3e3d0efbbd058 (patch) | |
| tree | acf99d7678da1696d31ac322c1bae49767f4641b | |
| parent | 9621ec0608e884984f199fc0dabbdb3886a11c99 (diff) | |
| download | ztop-c4ca679ab630d64f030f2529f6d3e3d0efbbd058.tar.gz | |
tui: a library of messages and widgets; add system and jobs views
The screen code moves to tui/ as a small toolkit: a cell buffer with a
diffing flush, a message loop in the shape of Bubble Tea (model, update,
view, ticks), and widgets for a viewport, a table, tabs, a text input,
a progress bar and a status line. ztop is now one user of it.
ztop grows two views beside storage: SYSTEM (CVS name, release, address
space count) and JOBS (one line per ASCB, from the CVT and ASVT, which
need no authorization). Views are tabs; each table keeps its own
selection and scroll position.
Follows the zash code style: doxygen headers, .clang-format, POSIX make.
| -rw-r--r-- | .clang-format | 8 | ||||
| -rw-r--r-- | .clang-tidy | 123 | ||||
| -rw-r--r-- | .clangd | 13 | ||||
| -rw-r--r-- | .gitignore | 6 | ||||
| -rw-r--r-- | Makefile | 65 | ||||
| -rw-r--r-- | src/sys.c | 86 | ||||
| -rw-r--r-- | src/sys.h | 43 | ||||
| -rw-r--r-- | src/tui.c | 552 | ||||
| -rw-r--r-- | src/tui.h | 93 | ||||
| -rw-r--r-- | src/vsm.c | 75 | ||||
| -rw-r--r-- | src/vsm.h | 41 | ||||
| -rw-r--r-- | src/ztop.c | 855 | ||||
| -rw-r--r-- | tests/test_vsm.c | 39 | ||||
| -rw-r--r-- | tui/Makefile | 38 | ||||
| -rw-r--r-- | tui/demo.c (renamed from tests/demo_tui.c) | 5 | ||||
| -rw-r--r-- | tui/test_tui.c | 161 | ||||
| -rw-r--r-- | tui/tui.c | 885 | ||||
| -rw-r--r-- | tui/tui.h | 198 |
18 files changed, 2126 insertions, 1160 deletions
diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..53048bd --- /dev/null +++ b/.clang-format @@ -0,0 +1,8 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +ColumnLimit: 80 +BreakBeforeBraces: Attach +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +IndentCaseLabels: false +SortIncludes: false diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..1962859 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,123 @@ +--- +# Checks for zash. Run with `make tidy`. Every check named here either +# finds real bugs in a shell (memory, signals, integer handling) or keeps the +# code in the style of the rest of the tree. Checks that disagree with the +# project's choices are switched off below, with the reason. +Checks: > + -*, + bugprone-*, + clang-analyzer-*, + cert-*, + misc-*, + performance-*, + portability-*, + readability-*, + -bugprone-easily-swappable-parameters, + -bugprone-assignment-in-if-condition, + -bugprone-branch-clone, + -bugprone-narrowing-conversions, + -bugprone-reserved-identifier, + -cert-dcl37-c, + -cert-dcl51-cpp, + -cert-err33-c, + -cert-err34-c, + -cert-msc24-c, + -cert-msc33-c, + -clang-analyzer-optin.performance.Padding, + -clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + -misc-include-cleaner, + -misc-no-recursion, + -readability-braces-around-statements, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-magic-numbers, + -readability-else-after-return, + -readability-isolate-declaration, + -readability-non-const-parameter, + -readability-avoid-unconditional-preprocessor-if, + -bugprone-multi-level-implicit-pointer-conversion, + -readability-avoid-nested-conditional-operator, + -readability-uppercase-literal-suffix, + -readability-math-missing-parentheses, + -bugprone-suspicious-string-compare, + -bugprone-not-null-terminated-result, + -clang-analyzer-security.insecureAPI.strcpy, + -cert-err33-c, + -cert-str34-c, + -bugprone-signal-handler, + -cert-sig30-c, + -bugprone-switch-missing-default-case, + -misc-header-include-cycle, + -readability-redundant-declaration, + -readability-named-parameter, + -readability-suspicious-call-argument, + -readability-function-size, + -readability-inconsistent-declaration-parameter-name, + -bugprone-implicit-widening-of-multiplication-result, + -performance-no-int-to-ptr + +# Not enabled, on purpose: +# bugprone-easily-swappable-parameters (sb_put(b, s, n) style is fine) +# bugprone-assignment-in-if-condition (the tree uses `if ((x = f()))` +# rarely and deliberately) +# cert-err33-c (unchecked close(), signal() and fflush() are +# deliberate on cleanup paths) +# cert-err34-c (parse_long wraps strtol with its own checks) +# cert-msc24-c/33-c (asks for _s functions and warns about asctime; +# neither exists on z/OS) +# misc-no-recursion (a tree-walking evaluator recurses by design; the +# depth is bounded by stack_low()) +# readability-braces-around-statements +# (one-line if bodies are the house style; the +# .clang-format keeps them on their own line) +# bugprone-multi-level-implicit-pointer-conversion +# (the qsort() comparison idiom) +# bugprone-suspicious-string-compare +# (`!strcmp(a, b)` is the house idiom for equality) +# readability-avoid-nested-conditional-operator, ...-literal-suffix, +# ...-math-missing-parentheses +# (style choices the tree does not follow) +# readability-magic-numbers, readability-identifier-length +# (noise in a parser and a bit-twiddling arithmetic +# scanner) + +WarningsAsErrors: '' +HeaderFilterRegex: '^.*/src/.*\.h$' +FormatStyle: file +SystemHeaders: false + +CheckOptions: + # ---- naming: snake_case everywhere, UPPER_CASE for constants ---------- + readability-identifier-naming.FunctionCase: lower_case + readability-identifier-naming.VariableCase: lower_case + readability-identifier-naming.ParameterCase: lower_case + readability-identifier-naming.LocalVariableCase: lower_case + readability-identifier-naming.GlobalVariableCase: lower_case + readability-identifier-naming.StructCase: lower_case + readability-identifier-naming.UnionCase: lower_case + readability-identifier-naming.EnumCase: lower_case + readability-identifier-naming.MemberCase: lower_case + readability-identifier-naming.TypedefCase: lower_case + readability-identifier-naming.MacroDefinitionCase: UPPER_CASE + readability-identifier-naming.EnumConstantCase: UPPER_CASE + readability-identifier-naming.GlobalConstantCase: lower_case + # `constexpr` is the C23 replacement for a `#define` constant, so it keeps + # the macro spelling: CSI_FIELD_LEN, MVS_DSN_MAX. A local + # `static constexpr` table is a variable in everything but storage. + readability-identifier-naming.ConstantCase: lower_case + readability-identifier-naming.ConstantIgnoredRegexp: '^[A-Z][A-Z0-9_]*$' + readability-identifier-naming.GlobalConstantIgnoredRegexp: '^[A-Z][A-Z0-9_]*$' + # A system macro that starts with an underscore is the system's spelling. + readability-identifier-naming.MacroDefinitionIgnoredRegexp: '^_.*$' + # Header guards look like ZASH_SHELL_H. + llvm-header-guard.HeaderFileExtensions: 'h' + + # ---- readability ------------------------------------------------------- + readability-implicit-bool-conversion.AllowIntegerConditions: true + readability-implicit-bool-conversion.AllowPointerConditions: true + + # ---- bugprone / misc --------------------------------------------------- + bugprone-signed-char-misuse.CharTypdefsToIgnore: '' + bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression: true + misc-unused-parameters.StrictMode: false +... @@ -0,0 +1,13 @@ +# clangd settings for ztop. There is no compile_commands.json here: the +# tree builds on z/OS with make and on Linux for the portable tests, so the +# flags are repeated here for the editor. +CompileFlags: + Add: [-Itui, -std=c23, -D_XOPEN_SOURCE=500, -D_POSIX_C_SOURCE=200112L, + -Wall, -Wextra, -Wshadow, -Wpedantic] +Diagnostics: + UnusedIncludes: Strict + MissingIncludes: Strict +Index: + Background: Build +InlayHints: + Enabled: false @@ -1,6 +1,10 @@ ztop src/*.o tests/test_vsm -tests/demo_tui +tui/*.o +tui/libtui.a +tui/test_tui +tui/demo CEEDUMP.* *.lst +compile_commands.json @@ -2,42 +2,51 @@ # ^ our linter reads this as shell: `NAME = value` and `$(CFLAGS)` are make. .POSIX: .SUFFIXES: +.SUFFIXES: .c .o -# ztop - what VSM has allocated, by subpool. +# ztop - what z/OS has where, for a systems programmer over ssh. # -# make build ./ztop -# make check run it against each area +# make build ./ztop (z/OS) +# make check run it against storage, system and jobs +# make test parser, library and system helpers, on any host +# make demo tui/demo, the library on its own # make clean remove what the targets above write # -# z/OS only: VSMLIST and the PSA do not exist elsewhere, so `make` on -# another host says so and stops. This tree is kept on Linux as a backup. +# z/OS only for ./ztop: VSMLIST, the PSA and the ASVT do not exist +# elsewhere, so `make` on another host says so and stops. This tree is +# kept on Linux as a backup and for the portable tests. # # The build is POSIX make, the make z/OS ships: no :=, no ?=, no ifeq, -# no $(shell), no pattern rules. gmake is not installed everywhere and -# /bin/make is not GNU make. One more z/OS make trait to know about: a -# recipe line holding a pipeline *and* a || spins it, so the pipeline is -# parenthesised (make/tests on the ztop machine depend on that). +# no $(shell), no pattern rules. One more z/OS make trait: a recipe line +# holding a pipeline *and* a || spins it, so the pipeline is +# parenthesised. -CC = ibm-clang -CFLAGS = -std=c23 -O2 -m32 -Wall -Wextra -Wshadow -Wpedantic \ - -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L -# The parser and the TUI framework have no z/OS dependency; the test and -# demo targets build them on the host so a Linux tree can check them. -TESTCC = ibm-clang -TESTFLAGS = -std=c17 -g -O1 -Wall -Wextra -Wshadow -Wpedantic \ - -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L +CC = ibm-clang +CSTD = -std=c23 +WARN = -Wall -Wextra -Wshadow -Wpedantic +CFLAGS = $(CSTD) $(WARN) -O2 -m32 -D_XOPEN_SOURCE=500 \ + -D_POSIX_C_SOURCE=200112L +CPPFLAGS = -Itui # AC(1) selects XPLINK. Quoted: the z/OS shell reads `(` in an # unquoted word as a syntax error. -LDFLAGS = -Wl,'-bAC(1)' +LDFLAGS = -Wl,'-bAC(1)' # The .S suffix sends the stub through clang's preprocessor; -P drops # the line markers HLASM would read as statements, and -fno-integrated-as # hands the result to HLASM. That path writes its own tagged temporary, # so the checked-out ASCII source needs no chtag first. -ASFLAGS = -fno-integrated-as -Xpreprocessor -P -SRC = src/ztop.c src/vsm.c src/tui.c +ASFLAGS = -fno-integrated-as -Xpreprocessor -P + +# The library is compiled into the program rather than linked as an +# archive: one binary, and the same sources build on Linux for the tests. +SRC = src/ztop.c src/vsm.c src/sys.c tui/tui.c OBJ = src/zvslist.o -HDR = src/vsm.h src/tui.h +HDR = src/vsm.h src/sys.h tui/tui.h + +# The portable half: no z/OS services, no terminal. +TESTCC = cc +TESTFLAGS = -std=c17 -g -O1 -Wall -Wextra -Wshadow -Wpedantic \ + -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L all: @(uname -s | grep OS/390 > /dev/null) || \ @@ -45,7 +54,7 @@ all: $(MAKE) ztop ztop: $(SRC) $(OBJ) $(HDR) - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(SRC) $(OBJ) + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o $@ $(SRC) $(OBJ) src/zvslist.o: src/zvslist.S $(CC) $(CFLAGS) $(ASFLAGS) -c -o $@ src/zvslist.S @@ -54,14 +63,16 @@ check: ztop ./ztop ./ztop -a sqa ./ztop -a pvt + ./ztop -j -# Portable checks: no VSMLIST, no terminal. -test: tests/test_vsm.c src/vsm.c src/vsm.h +test: tests/test_vsm.c src/vsm.c tui/test_tui.c tui/tui.c $(TESTCC) $(TESTFLAGS) -o tests/test_vsm tests/test_vsm.c src/vsm.c ./tests/test_vsm + $(TESTCC) $(TESTFLAGS) -Itui -o tui/test_tui tui/test_tui.c tui/tui.c + ./tui/test_tui -demo: tests/demo_tui.c src/tui.c src/tui.h - $(TESTCC) $(TESTFLAGS) -o tests/demo_tui tests/demo_tui.c src/tui.c +demo: tui/demo.c tui/tui.c + $(TESTCC) $(TESTFLAGS) -Itui -o tui/demo tui/demo.c tui/tui.c clean: - rm -f ztop $(OBJ) tests/test_vsm tests/demo_tui + rm -f ztop $(OBJ) tests/test_vsm tui/test_tui tui/demo diff --git a/src/sys.c b/src/sys.c new file mode 100644 index 0000000..67c836b --- /dev/null +++ b/src/sys.c @@ -0,0 +1,86 @@ +/** + * @file sys.c + * @brief System identity and address spaces. + * + * The only z/OS-specific reads are four documented control blocks: the + * CVT at PSA+0x10, CVTSNAME at CVT+0x154, CVTASVT at CVT+0x22C, and the + * ASVT/ASCB chain below it. Everything else (host name, release) comes + * from the C library, so the structure is the same on any host. + */ +#include "sys.h" + +#include <string.h> +#include <sys/utsname.h> +#include <unistd.h> + +#ifdef __MVS__ +#include <stdint.h> + +/** @brief Read a big-endian halfword from an absolute address. */ +static uint32_t rd32(uintptr_t a) { + uint32_t v; + + memcpy(&v, (const void *)a, sizeof v); + return v; +} + +/** @brief Read one byte from an absolute address. */ +static unsigned char rd8(uintptr_t a) { + unsigned char v; + + memcpy(&v, (const void *)a, 1); + return v; +} + +/** @brief Copy an EBCDIC field, blank padded, into ASCII. */ +static void ebcdic(char *dst, size_t dstlen, const void *src, size_t srclen) { + size_t n; + + if (dstlen == 0) + return; + n = srclen < dstlen - 1 ? srclen : dstlen - 1; + if (n > 0) + __e2a_l(dst, src, n); + dst[n] = '\0'; + while (n > 0 && dst[n - 1] == ' ') + dst[--n] = '\0'; +} +#endif + +bool zsys_read(struct zsys *z) { +#ifdef __MVS__ + uintptr_t cvt, asvt; + uint32_t maxu, entry; + unsigned int i; + + memset(z, 0, sizeof *z); + cvt = rd32(0x10); + asvt = rd32(cvt + 0x22C); + if (cvt == 0 || asvt == 0) + return false; + + ebcdic(z->sysname, sizeof z->sysname, (const void *)(cvt + 0x154), 8); + maxu = rd32(asvt + 0x204); + z->slots = maxu > 0x10000 ? 0x10000 : maxu; + for (i = 0; i < z->slots && z->njobs < ZJOB_MAX; i++) { + struct zjob *j = &z->job[z->njobs]; + uint32_t namep; + + entry = rd32(asvt + 0x210 + (uintptr_t)i * 4); + if (entry & 0x80000000u) + continue; /* ASID is free */ + j->ascb = entry; + j->asid = rd8((uintptr_t)entry + 0x24); + namep = rd32((uintptr_t)entry + 0xB0); + if (namep == 0) + continue; + ebcdic(j->name, sizeof j->name, (const void *)(uintptr_t)namep, 8); + if (j->name[0] != '\0') + z->njobs++; + } + return true; +#else + (void)z; + return false; +#endif +} diff --git a/src/sys.h b/src/sys.h new file mode 100644 index 0000000..e55c195 --- /dev/null +++ b/src/sys.h @@ -0,0 +1,43 @@ +/** + * @file sys.h + * @brief The system's name and its address spaces, from the CVT and ASVT. + * + * Both are documented programming interfaces: CVTASVT at CVT+0x22C, the + * ASVT with ASVTMAXU at +0x204 and ASVTENTY at +0x210, and the ASCB + * fields ASCBASID, ASCBJBNS. Reading them needs only problem state, so + * this is the jobs view without an authorized service. + */ +#ifndef ZTOP_SYS_H +#define ZTOP_SYS_H + +#include <stdbool.h> +#include <stdint.h> + +#define ZJOB_MAX 512 + +/** @brief One address space. */ +struct zjob { + unsigned int asid; + uint32_t ascb; + char name[9]; +}; + +/** @brief What the system view shows. */ +struct zsys { + char sysname[9]; + char host[65]; + char os[64]; + char machine[32]; + unsigned int slots; /**< ASVT entries, used or free */ + int njobs; + struct zjob job[ZJOB_MAX]; +}; + +/** + * @brief Fill @p z from the CVT and the ASVT. + * @param z Where to write. + * @return false when this is not z/OS, with @c z untouched. + */ +bool zsys_read(struct zsys *z); + +#endif diff --git a/src/tui.c b/src/tui.c deleted file mode 100644 index ef1bf43..0000000 --- a/src/tui.c +++ /dev/null @@ -1,552 +0,0 @@ -/** - * @file tui.c - * @brief See tui.h. One output buffer per frame, one diff against the last. - */ -#include "tui.h" - -#include <errno.h> -#include <signal.h> -#include <stdarg.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/ioctl.h> -#include <sys/select.h> -#include <unistd.h> - -#ifdef __MVS__ -#define ESCS "\x27" /* EBCDIC ESC; the tty converts it to 0x1b */ -#define ESC_CHAR 0x27u /* what a key press of ESC looks like here */ -#else -#define ESCS "\x1b" -#define ESC_CHAR 0x1bu -#endif - -#define ALT_ON ESCS "[?1049h" -#define ALT_OFF ESCS "[?1049l" -#define CUR_OFF ESCS "[?25l" -#define CUR_ON ESCS "[?25h" -#define CLEAR ESCS "[H" ESCS "[2J" -#define RESET ESCS "[0m" - -static struct tui *g_tui; -static volatile sig_atomic_t g_winch; - -static void wr(int fd, const void *buf, size_t n) -{ - const char *p = buf; - - while (n > 0) { - ssize_t k = write(fd, p, n); - if (k < 0 && errno == EINTR) - continue; - if (k <= 0) - return; - p += (size_t)k; - n -= (size_t)k; - } -} - -static void restore(struct tui *t) -{ - if (!t->open) - return; - wr(t->fd_out, RESET CUR_ON ALT_OFF, strlen(RESET CUR_ON ALT_OFF)); - (void)tcsetattr(t->fd_in, TCSANOW, &t->orig); -} - -static void on_winch(int sig) -{ - (void)sig; - g_winch = 1; -} - -static void on_term(int sig) -{ - if (g_tui != NULL) - restore(g_tui); - _exit(128 + sig); -} - -static void out_flush(struct tui *t) -{ - if (t->olen > 0) { - wr(t->fd_out, t->out, (size_t)t->olen); - t->olen = 0; - } -} - -static void out(struct tui *t, const char *s, size_t n) -{ - if (t->olen + (int)n > (int)sizeof t->out) - out_flush(t); - if (n > sizeof t->out) { - wr(t->fd_out, s, n); - return; - } - memcpy(t->out + t->olen, s, n); - t->olen += (int)n; -} - -static void outs(struct tui *t, const char *s) -{ - out(t, s, strlen(s)); -} - -static void outf(struct tui *t, const char *fmt, ...) -{ - char b[64]; - va_list ap; - int n; - - va_start(ap, fmt); - n = vsnprintf(b, sizeof b, fmt, ap); - va_end(ap); - if (n > 0) - out(t, b, (size_t)n < sizeof b ? (size_t)n : sizeof b - 1); -} - -static void sgr(struct tui *t, int fg, int bg, int attr) -{ - char b[40]; - int n = snprintf(b, sizeof b, "%s[0", ESCS); - - if (attr & TUI_BOLD) - n += snprintf(b + n, sizeof b - (size_t)n, ";1"); - if (attr & TUI_DIM) - n += snprintf(b + n, sizeof b - (size_t)n, ";2"); - if (attr & TUI_UNDERLINE) - n += snprintf(b + n, sizeof b - (size_t)n, ";4"); - if (attr & TUI_REVERSE) - n += snprintf(b + n, sizeof b - (size_t)n, ";7"); - n += snprintf(b + n, sizeof b - (size_t)n, ";3%d;4%dm", fg, bg); - out(t, b, (size_t)n); -} - -/* Ask the terminal where the cursor is; its answer is the only size z/OS - * gives us. Returns false if the terminal does not answer. */ -static bool cpr_size(int in, int outfd, int *w, int *h) -{ - unsigned char b[64]; - int n = 0; - bool got = false, esc = false, csi = false; - int vals[2] = { 0, 0 }, nv = 0, v = 0; - - wr(outfd, ESCS "[6n", sizeof ESCS "[6n" - 1); - for (int rounds = 0; rounds < 30 && !got; rounds++) { - fd_set f; - struct timeval tv = { 0, 10000 }; - - FD_ZERO(&f); - FD_SET(in, &f); - int r = select(in + 1, &f, NULL, NULL, &tv); - if (r < 0 && errno == EINTR) - continue; - if (r <= 0) - continue; - ssize_t k = read(in, b + n, sizeof b - (size_t)n); - if (k <= 0) - continue; - for (ssize_t i = 0; i < k; i++) { - unsigned char c = b[n + (size_t)i]; - if (!esc) { - if (c == ESC_CHAR) - esc = true; - continue; - } - if (!csi) { - if (c == '[') - csi = true; - else if (c != ESC_CHAR) - esc = false; - continue; - } - if (c >= '0' && c <= '9') { - v = v * 10 + (c - '0'); - } else if (c == ';' && nv == 0) { - vals[nv++] = v; - v = 0; - } else if (c == 'R') { - vals[nv++] = v; - got = true; - break; - } else { - esc = csi = false; - nv = v = 0; - } - } - n = 0; - } - if (!got || nv < 2 || vals[0] <= 0 || vals[1] <= 0) - return false; - *h = vals[0]; - *w = vals[1]; - return true; -} - -static void probe_size(struct tui *t, int *w, int *h) -{ - struct winsize ws; - - *w = 80; - *h = 24; - if (ioctl(t->fd_out, TIOCGWINSZ, &ws) == 0 && - ws.ws_col > 0 && ws.ws_row > 0) { - *w = ws.ws_col; - *h = ws.ws_row; - } else if (!cpr_size(t->fd_in, t->fd_out, w, h)) { - const char *c = getenv("COLUMNS"); - const char *l = getenv("LINES"); - if (c != NULL && atoi(c) > 0) - *w = atoi(c); - if (l != NULL && atoi(l) > 0) - *h = atoi(l); - } - if (*w > TUI_MAX_W) - *w = TUI_MAX_W; - if (*h > TUI_MAX_H) - *h = TUI_MAX_H; - if (*w < 20) - *w = 80; - if (*h < 5) - *h = 24; -} - -bool tui_resize(struct tui *t) -{ - int w, h; - - probe_size(t, &w, &h); - if (w == t->w && h == t->h) - return false; - - struct tui_cell *cur = calloc((size_t)w * (size_t)h, sizeof *cur); - struct tui_cell *old = calloc((size_t)w * (size_t)h, sizeof *old); - if (cur == NULL || old == NULL) { - free(cur); - free(old); - return false; - } - free(t->cur); - free(t->old); - t->cur = cur; - t->old = old; - t->w = w; - t->h = h; - t->full = true; - tui_clear(t); - return true; -} - -bool tui_open(struct tui *t) -{ - struct termios r; - - memset(t, 0, sizeof *t); - t->fd_in = 0; - t->fd_out = 1; - if (!isatty(t->fd_in) || !isatty(t->fd_out)) - return false; - if (tcgetattr(t->fd_in, &t->orig) != 0) - return false; - r = t->orig; - r.c_lflag &= (tcflag_t)~(ICANON | ECHO | ISIG | IEXTEN); - r.c_iflag &= (tcflag_t)~(IXON | ICRNL | BRKINT | INPCK | ISTRIP); - r.c_oflag &= (tcflag_t)~OPOST; - r.c_cc[VMIN] = 0; - r.c_cc[VTIME] = 0; - if (tcsetattr(t->fd_in, TCSANOW, &r) != 0) - return false; - - t->open = true; - g_tui = t; - g_winch = 0; - (void)signal(SIGTERM, on_term); - (void)signal(SIGINT, on_term); - (void)signal(SIGHUP, on_term); - (void)signal(SIGQUIT, on_term); -#ifdef SIGWINCH - (void)signal(SIGWINCH, on_winch); -#endif - outs(t, ALT_ON CUR_OFF CLEAR); - out_flush(t); - if (!tui_resize(t)) { - restore(t); - t->open = false; - g_tui = NULL; - return false; - } - return true; -} - -void tui_close(struct tui *t) -{ - if (!t->open) - return; - restore(t); - t->open = false; - g_tui = NULL; - free(t->cur); - free(t->old); - t->cur = NULL; - t->old = NULL; -} - -void tui_size(struct tui *t, int *w, int *h) -{ - *w = t->w; - *h = t->h; -} - -void tui_clear(struct tui *t) -{ - int n = t->w * t->h; - - for (int i = 0; i < n; i++) { - t->cur[i].ch = ' '; - t->cur[i].fg = 7; - t->cur[i].bg = 0; - t->cur[i].attr = 0; - } -} - -void tui_fill(struct tui *t, int x, int y, int w, int h, char ch, tui_style st) -{ - if (x < 0) { w += x; x = 0; } - if (y < 0) { h += y; y = 0; } - if (x + w > t->w) w = t->w - x; - if (y + h > t->h) h = t->h - y; - if (w <= 0 || h <= 0) - return; - for (int j = y; j < y + h; j++) { - struct tui_cell *row = t->cur + (size_t)j * (size_t)t->w; - for (int i = x; i < x + w; i++) { - row[i].ch = (unsigned char)ch; - row[i].fg = st.fg; - row[i].bg = st.bg; - row[i].attr = st.attr; - } - } -} - -void tui_put(struct tui *t, int x, int y, const char *s, int maxw, tui_style st) -{ - if (y < 0 || y >= t->h) - return; - struct tui_cell *row = t->cur + (size_t)y * (size_t)t->w; - for (int i = 0; s[i] != '\0' && x < t->w; i++, x++) { - unsigned char c = (unsigned char)s[i]; - if (maxw > 0 && i >= maxw) - break; - if (x < 0) - continue; - if (c < 0x20) - c = '?'; - row[x].ch = c; - row[x].fg = st.fg; - row[x].bg = st.bg; - row[x].attr = st.attr; - } -} - -void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st, - const char *fmt, ...) -{ - char b[512]; - va_list ap; - - va_start(ap, fmt); - (void)vsnprintf(b, sizeof b, fmt, ap); - va_end(ap); - tui_put(t, x, y, b, maxw, st); -} - -void tui_box(struct tui *t, int x, int y, int w, int h, tui_style st) -{ - if (w < 2 || h < 2) - return; - for (int i = 1; i < w - 1; i++) { - tui_put(t, x + i, y, "-", 1, st); - tui_put(t, x + i, y + h - 1, "-", 1, st); - } - for (int j = 1; j < h - 1; j++) { - tui_put(t, x, y + j, "|", 1, st); - tui_put(t, x + w - 1, y + j, "|", 1, st); - } - tui_put(t, x, y, "+", 1, st); - tui_put(t, x + w - 1, y, "+", 1, st); - tui_put(t, x, y + h - 1, "+", 1, st); - tui_put(t, x + w - 1, y + h - 1, "+", 1, st); -} - -void tui_flush(struct tui *t) -{ - int lfg = -1, lbg = -1, la = -1; - - if (!t->open) - return; - if (t->full) { - outs(t, CLEAR); - memset(t->old, 0, (size_t)t->w * (size_t)t->h * sizeof *t->old); - t->full = false; - } - for (int y = 0; y < t->h; y++) { - struct tui_cell *row = t->cur + (size_t)y * (size_t)t->w; - struct tui_cell *orow = t->old + (size_t)y * (size_t)t->w; - int x = 0; - - while (x < t->w) { - while (x < t->w && row[x].ch == orow[x].ch && - row[x].fg == orow[x].fg && row[x].bg == orow[x].bg && - row[x].attr == orow[x].attr) - x++; - if (x >= t->w) - break; - int start = x; - while (x < t->w && !(row[x].ch == orow[x].ch && - row[x].fg == orow[x].fg && - row[x].bg == orow[x].bg && - row[x].attr == orow[x].attr)) - x++; - outf(t, "%s[%d;%dH", ESCS, y + 1, start + 1); - for (int i = start; i < x; i++) { - if (row[i].fg != lfg || row[i].bg != lbg || row[i].attr != la) { - sgr(t, row[i].fg, row[i].bg, row[i].attr); - lfg = row[i].fg; - lbg = row[i].bg; - la = row[i].attr; - } - char c = (char)(row[i].ch != 0 ? row[i].ch : ' '); - out(t, &c, 1); - } - } - } - memcpy(t->old, t->cur, (size_t)t->w * (size_t)t->h * sizeof *t->cur); - out_flush(t); -} - -static void shift_in(struct tui *t, int n) -{ - if (n >= t->inlen) { - t->inlen = 0; - return; - } - memmove(t->in, t->in + n, (size_t)(t->inlen - n)); - t->inlen -= n; -} - -static int decode(struct tui *t) -{ - unsigned char *b = t->in; - - if (t->inlen == 0) - return TUI_KEY_NONE; - if (b[0] != ESC_CHAR) { - int k = b[0]; - shift_in(t, 1); - return k; - } - if (t->inlen < 2) - return TUI_KEY_NONE; - if (b[1] != '[') { - shift_in(t, 1); - return TUI_KEY_ESC; - } - if (t->inlen < 3) - return TUI_KEY_NONE; - - int k = TUI_KEY_NONE; - switch (b[2]) { - case 'A': k = TUI_KEY_UP; break; - case 'B': k = TUI_KEY_DOWN; break; - case 'C': k = TUI_KEY_RIGHT; break; - case 'D': k = TUI_KEY_LEFT; break; - case 'H': k = TUI_KEY_HOME; break; - case 'F': k = TUI_KEY_END; break; - default: break; - } - if (k != TUI_KEY_NONE) { - shift_in(t, 3); - return k; - } - if (b[2] >= '1' && b[2] <= '9') { - int v = 0, i = 2; - while (i < t->inlen && b[i] >= '0' && b[i] <= '9') { - v = v * 10 + (b[i] - '0'); - i++; - } - if (i >= t->inlen) - return TUI_KEY_NONE; /* wait for the final byte */ - if (i < t->inlen && b[i] == '~') { - switch (v) { - case 1: case 7: k = TUI_KEY_HOME; break; - case 2: k = TUI_KEY_NONE; break; - case 3: k = TUI_KEY_DEL; break; - case 4: case 8: k = TUI_KEY_END; break; - case 5: k = TUI_KEY_PGUP; break; - case 6: k = TUI_KEY_PGDN; break; - default: break; - } - shift_in(t, i + 1); - return k; - } - } - /* Unknown CSI: drop the introducer and try again, so a paste of - * unsupported sequences does not turn into random commands. */ - shift_in(t, 3); - return TUI_KEY_NONE; -} - -int tui_key(struct tui *t, int timeout_ms) -{ - if (g_winch) { - g_winch = 0; - return TUI_KEY_RESIZE; - } - for (;;) { - if (t->inlen > 0) { - int k = decode(t); - if (k != TUI_KEY_NONE) - return k; - } - if (g_winch) { - g_winch = 0; - return TUI_KEY_RESIZE; - } - int wait = (t->inlen > 0) ? 30 : timeout_ms; - fd_set f; - struct timeval tv, *ptv = NULL; - - FD_ZERO(&f); - FD_SET(t->fd_in, &f); - if (wait >= 0) { - tv.tv_sec = wait / 1000; - tv.tv_usec = (wait % 1000) * 1000; - ptv = &tv; - } - int r = select(t->fd_in + 1, &f, NULL, NULL, ptv); - if (r < 0) { - if (errno == EINTR) - continue; - return TUI_KEY_NONE; - } - if (r == 0) { - if (t->inlen > 0) { - if (t->inlen == 1 && t->in[0] == ESC_CHAR) { - t->inlen = 0; - return TUI_KEY_ESC; - } - t->inlen = 0; - } - return TUI_KEY_NONE; - } - ssize_t n = read(t->fd_in, t->in + t->inlen, - sizeof t->in - (size_t)t->inlen); - if (n <= 0) { - if (n < 0 && errno == EINTR) - continue; - return TUI_KEY_ESC; - } - t->inlen += (int)n; - } -} diff --git a/src/tui.h b/src/tui.h deleted file mode 100644 index b68f09e..0000000 --- a/src/tui.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file tui.h - * @brief A small cell-based terminal UI: double buffer, diff flush, raw keys. - * - * Deliberately no ncurses and no terminfo. Output is plain ANSI (xterm and - * anything that copies it), input is decoded by hand. Only bytes are stored, - * so a cell is one character wide: ASCII art, not UTF-8 box drawing. On z/OS - * the C compiler's EBCDIC literals are converted by the tty, which is why - * TUI_ESC below is 0x27 there and 0x1b everywhere else. - */ -#ifndef ZTOP_TUI_H -#define ZTOP_TUI_H - -#include <stdbool.h> -#include <termios.h> - -struct tui_cell { - unsigned char ch; - unsigned char fg; - unsigned char bg; - unsigned char attr; -}; - -typedef struct { - unsigned char fg; /**< 0-7, 7 is white */ - unsigned char bg; /**< 0-7, 0 is black */ - unsigned char attr; /**< TUI_BOLD / TUI_REVERSE / TUI_DIM / TUI_UNDERLINE */ -} tui_style; - -#define TUI_BOLD 1u -#define TUI_REVERSE 2u -#define TUI_DIM 4u -#define TUI_UNDERLINE 8u - -#define TUI_STYLE(f, b, a) ((tui_style){ (unsigned char)(f), (unsigned char)(b), (unsigned char)(a) }) -#define TUI_PLAIN TUI_STYLE(7, 0, 0) -#define TUI_TITLE TUI_STYLE(7, 4, TUI_BOLD) -#define TUI_LABEL TUI_STYLE(6, 0, 0) -#define TUI_GOOD TUI_STYLE(2, 0, 0) -#define TUI_WARN TUI_STYLE(3, 0, 0) -#define TUI_BAD TUI_STYLE(1, 0, TUI_BOLD) - -enum { - TUI_KEY_NONE = -1, - TUI_KEY_ESC = 256, - TUI_KEY_UP, - TUI_KEY_DOWN, - TUI_KEY_LEFT, - TUI_KEY_RIGHT, - TUI_KEY_HOME, - TUI_KEY_END, - TUI_KEY_PGUP, - TUI_KEY_PGDN, - TUI_KEY_DEL, - TUI_KEY_RESIZE -}; - -#define TUI_MAX_W 500 -#define TUI_MAX_H 200 - -struct tui { - int w, h; - int fd_in, fd_out; - struct tui_cell *cur; - struct tui_cell *old; - bool full; - bool open; - struct termios orig; - unsigned char in[64]; - int inlen; - char out[32768]; - int olen; -}; - -bool tui_open(struct tui *t); -void tui_close(struct tui *t); - -/** @brief Re-query the size; returns true when it changed and the buffers moved. */ -bool tui_resize(struct tui *t); -void tui_size(struct tui *t, int *w, int *h); - -void tui_clear(struct tui *t); -void tui_fill(struct tui *t, int x, int y, int w, int h, char ch, tui_style st); -void tui_put(struct tui *t, int x, int y, const char *s, int maxw, tui_style st); -void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st, - const char *fmt, ...); -void tui_box(struct tui *t, int x, int y, int w, int h, tui_style st); -void tui_flush(struct tui *t); - -/** @brief Wait up to @p timeout_ms (-1 = forever) for a key. */ -int tui_key(struct tui *t, int timeout_ms); - -#endif @@ -15,14 +15,12 @@ struct rd { bool bad; }; -static uint32_t be32(const unsigned char *p) -{ +static uint32_t be32(const unsigned char *p) { return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3]; } -static uint32_t rd32(struct rd *r) -{ +static uint32_t rd32(struct rd *r) { if (r->bad || r->off > r->len || r->len - r->off < 4) { r->bad = true; return 0; @@ -32,8 +30,7 @@ static uint32_t rd32(struct rd *r) return v; } -static unsigned rd8(struct rd *r) -{ +static unsigned rd8(struct rd *r) { if (r->bad || r->off >= r->len) { r->bad = true; return 0; @@ -41,8 +38,7 @@ static unsigned rd8(struct rd *r) return r->p[r->off++]; } -static bool fail(struct vsm_info *v, const char *what, unsigned off) -{ +static bool fail(struct vsm_info *v, const char *what, unsigned off) { (void)snprintf(v->err, sizeof v->err, "%s at offset %u", what, off); return false; } @@ -50,15 +46,13 @@ static bool fail(struct vsm_info *v, const char *what, unsigned off) /* Every block needs at least its 8-byte address/length pair. A count larger * than the remaining bytes can never be honest, and it would make us loop * for a long time on a corrupt or truncated data area. */ -static bool count_ok(const struct rd *r, uint32_t n) -{ +static bool count_ok(const struct rd *r, uint32_t n) { if (r->off > r->len) return false; return n <= (r->len - r->off) / 8; } -void vsm_reset(struct vsm_info *v, unsigned area, unsigned space) -{ +void vsm_reset(struct vsm_info *v, unsigned area, unsigned space) { memset(v, 0, sizeof *v); v->area = area; v->space = space; @@ -66,8 +60,7 @@ void vsm_reset(struct vsm_info *v, unsigned area, unsigned space) } bool vsm_work_data(const unsigned char *work, unsigned wlen, - const unsigned char **data, unsigned *len) -{ + const unsigned char **data, unsigned *len) { uint32_t addr, dlen; uintptr_t base = (uintptr_t)work; @@ -89,8 +82,8 @@ bool vsm_work_data(const unsigned char *work, unsigned wlen, return true; } -static struct vsm_subpool *sub_find(struct vsm_info *v, unsigned id, uint32_t tcb) -{ +static struct vsm_subpool *sub_find(struct vsm_info *v, unsigned id, + uint32_t tcb) { for (int i = 0; i < v->nsub; i++) if (v->sub[i].id == id && v->sub[i].tcb == tcb) return &v->sub[i]; @@ -108,8 +101,8 @@ static struct vsm_subpool *sub_find(struct vsm_info *v, unsigned id, uint32_t tc /* One allocated block, plus its free descriptors when SPACE=FREE. * Collected into s when there is room, and into the area totals always. */ -static bool parse_block(struct rd *r, struct vsm_info *v, struct vsm_subpool *s) -{ +static bool parse_block(struct rd *r, struct vsm_info *v, + struct vsm_subpool *s) { unsigned off = r->off; uint32_t addr = rd32(r); uint32_t blen = rd32(r); @@ -121,12 +114,14 @@ static bool parse_block(struct rd *r, struct vsm_info *v, struct vsm_subpool *s) if (v->space == VSM_FREE) { uint32_t nf = rd32(r); if (r->bad) - return fail(v, "free-descriptor count past end of data", r->off - 4); + return fail(v, "free-descriptor count past end of data", + r->off - 4); if (!count_ok(r, nf)) - return fail(v, "free-descriptor count larger than the data area", r->off - 4); + return fail(v, "free-descriptor count larger than the data area", + r->off - 4); for (uint32_t i = 0; i < nf; i++) { unsigned foff = r->off; - (void)rd32(r); /* free block address */ + (void)rd32(r); /* free block address */ uint32_t flen = rd32(r); if (r->bad) return fail(v, "free descriptor past end of data", foff); @@ -134,7 +129,7 @@ static bool parse_block(struct rd *r, struct vsm_info *v, struct vsm_subpool *s) } } if (bfree > blen) - bfree = blen; /* never report negative use */ + bfree = blen; /* never report negative use */ uint64_t used = (uint64_t)blen - bfree; v->blocks++; @@ -163,8 +158,7 @@ static bool parse_block(struct rd *r, struct vsm_info *v, struct vsm_subpool *s) return true; } -static bool parse_alloc_section(struct rd *r, struct vsm_info *v) -{ +static bool parse_alloc_section(struct rd *r, struct vsm_info *v) { uint32_t nsub = rd32(r); if (r->bad) return fail(v, "subpool count past end of data", r->off - 4); @@ -188,16 +182,17 @@ static bool parse_alloc_section(struct rd *r, struct vsm_info *v) return fail(v, "subpool descriptor length is out of range", off); if ((uint64_t)off + dlen > r->len) return fail(v, "subpool descriptor length past end of data", off); - r->off = off + dlen; /* skip trailing reserved bytes */ + r->off = off + dlen; /* skip trailing reserved bytes */ uint32_t nblocks = rd32(r); if (r->bad) - return fail(v, "allocated-block count past end of data", r->off - 4); + return fail(v, "allocated-block count past end of data", + r->off - 4); if (!count_ok(r, nblocks)) - return fail(v, "allocated-block count larger than the data area", r->off - 4); + return fail(v, "allocated-block count larger than the data area", + r->off - 4); - struct vsm_subpool *s = sub_find(v, id, - v->area == VSM_PVT ? tcb : 0); + struct vsm_subpool *s = sub_find(v, id, v->area == VSM_PVT ? tcb : 0); if (s != NULL) { s->key = flags & 0x0Fu; s->flags = flags; @@ -209,9 +204,9 @@ static bool parse_alloc_section(struct rd *r, struct vsm_info *v) return true; } -bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, unsigned len) -{ - struct rd r = { data, len, 0, false }; +bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, + unsigned len) { + struct rd r = {data, len, 0, false}; if (v->area == VSM_PVT) { uint32_t n = rd32(&r); @@ -222,7 +217,7 @@ bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, unsigned len v->tcbs += n; for (uint32_t t = 0; t < n; t++) { unsigned off = r.off; - (void)rd32(&r); /* TCB address, for progress only */ + (void)rd32(&r); /* TCB address, for progress only */ if (r.bad) return fail(v, "TCB address past end of data", off); if (!parse_alloc_section(&r, v)) @@ -234,9 +229,9 @@ bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, unsigned len return true; } -bool vsm_parse_unalloc(struct vsm_info *v, const unsigned char *data, unsigned len) -{ - struct rd r = { data, len, 0, false }; +bool vsm_parse_unalloc(struct vsm_info *v, const unsigned char *data, + unsigned len) { + struct rd r = {data, len, 0, false}; uint32_t nreg = rd32(&r); if (r.bad) @@ -259,12 +254,14 @@ bool vsm_parse_unalloc(struct vsm_info *v, const unsigned char *data, unsigned l uint32_t nblocks = rd32(&r); if (r.bad) - return fail(v, "unallocated-block count past end of data", r.off - 4); + return fail(v, "unallocated-block count past end of data", + r.off - 4); if (!count_ok(&r, nblocks)) - return fail(v, "unallocated-block count larger than the data area", r.off - 4); + return fail(v, "unallocated-block count larger than the data area", + r.off - 4); for (uint32_t b = 0; b < nblocks; b++) { unsigned boff = r.off; - (void)rd32(&r); /* unallocated block address */ + (void)rd32(&r); /* unallocated block address */ uint32_t blen = rd32(&r); if (r.bad) return fail(v, "unallocated block past end of data", boff); @@ -25,18 +25,19 @@ enum vsm_space { VSM_FREE = 1, VSM_UNALLOC = 2 }; /** @brief Region descriptors kept for display (CSA/ECSA/RUCSA, PVT regions). */ #define VSM_MAX_REGION 16 -/** @brief One subpool: allocated blocks, the free space in them, the real use. */ +/** @brief One subpool: allocated blocks, the free space in them, the real use. + */ struct vsm_subpool { - unsigned id; /**< translated subpool number */ - unsigned key; /**< storage key from the descriptor's flag byte */ - unsigned flags; /**< the descriptor's flag byte */ - uint32_t tcb; /**< owning TCB for PVT, zero for common areas */ - uint64_t used; /**< block bytes minus free space inside the blocks */ - uint64_t free; /**< free space inside allocated blocks */ - uint64_t foot; /**< footprint: sum of allocated block lengths */ - uint64_t largest; /**< largest allocated block */ - uint32_t lo, hi; /**< address range of the allocated blocks */ - unsigned blocks; /**< number of allocated blocks */ + unsigned id; /**< translated subpool number */ + unsigned key; /**< storage key from the descriptor's flag byte */ + unsigned flags; /**< the descriptor's flag byte */ + uint32_t tcb; /**< owning TCB for PVT, zero for common areas */ + uint64_t used; /**< block bytes minus free space inside the blocks */ + uint64_t free; /**< free space inside allocated blocks */ + uint64_t foot; /**< footprint: sum of allocated block lengths */ + uint64_t largest; /**< largest allocated block */ + uint32_t lo, hi; /**< address range of the allocated blocks */ + unsigned blocks; /**< number of allocated blocks */ }; /** @brief A region descriptor (an unallocated range, or a PVT region). */ @@ -47,13 +48,13 @@ struct vsm_region { /** @brief Everything one area reports, accumulated over continuation calls. */ struct vsm_info { - unsigned area; /**< enum vsm_area */ - unsigned space; /**< enum vsm_space of the last parse */ - unsigned tcbs; /**< PVT: TCBs listed */ + unsigned area; /**< enum vsm_area */ + unsigned space; /**< enum vsm_space of the last parse */ + unsigned tcbs; /**< PVT: TCBs listed */ int nsub; struct vsm_subpool sub[VSM_MAX_SUB]; - unsigned blocks; /**< allocated blocks in the area */ + unsigned blocks; /**< allocated blocks in the area */ uint64_t used; uint64_t free; uint64_t foot; @@ -61,12 +62,12 @@ struct vsm_info { uint32_t lo, hi; unsigned unalloc_blocks; - uint64_t unalloc; /**< unallocated bytes (CSA/PVT only) */ + uint64_t unalloc; /**< unallocated bytes (CSA/PVT only) */ uint64_t largest_unalloc; int nregion; struct vsm_region region[VSM_MAX_REGION]; - bool truncated; /**< more subpools than VSM_MAX_SUB; totals still right */ + bool truncated; /**< more subpools than VSM_MAX_SUB; totals still right */ bool unalloc_valid; /**< the UNALLOC request succeeded */ char err[160]; /**< why the last parse or service call failed */ }; @@ -94,9 +95,11 @@ bool vsm_work_data(const unsigned char *work, unsigned wlen, * @return false on a stream that does not match the documented layout, with * v::err set and the offset in it. */ -bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, unsigned len); +bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data, + unsigned len); /** @brief Parse an unallocated-storage data area (CSA or PVT only). */ -bool vsm_parse_unalloc(struct vsm_info *v, const unsigned char *data, unsigned len); +bool vsm_parse_unalloc(struct vsm_info *v, const unsigned char *data, + unsigned len); #endif @@ -1,6 +1,10 @@ /** * @file ztop.c - * @brief Storage overview for z/OS: one-shot reports and a full-screen view. + * @brief What z/OS has where: storage by subpool, the system, and jobs. + * + * One-shot reports for scripts and a full-screen view for people. The + * view is built on libtui, which knows nothing about z/OS: ztop supplies + * the model, the messages and the tables. */ #include <stdbool.h> #include <stddef.h> @@ -8,13 +12,15 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/utsname.h> #include <time.h> #include <unistd.h> +#include "sys.h" #include "tui.h" #include "vsm.h" -#define ZTOP_VERSION "0.2" +#define ZTOP_VERSION "0.3" #define WORK_SIZE (1024u * 1024u) #if defined(__MVS__) @@ -23,8 +29,9 @@ extern int zvslist(void *) __asm__("ZVSLIST"); #pragma linkage(zvslist, OS) -/* The 31-bit request block. R13 is saved by the stub, so the save area has - * to live in storage the C compiler gives us, not in the read-only CSECT. */ +/* The 31-bit request block. R13 is saved by the stub, so the save area + * has to live in storage the C compiler gives us, not in the read-only + * CSECT. */ struct zreq { int area; unsigned len; @@ -41,11 +48,11 @@ _Static_assert(offsetof(struct zreq, space) == 168, "zreq.space"); static unsigned char work[WORK_SIZE] __attribute__((aligned(8))); #endif -static const char *const area_name[] = { "csa", "sqa", "lsqa", "pvt" }; -static const char *const area_upper[] = { "CSA", "SQA", "LSQA", "PVT" }; +static const char *const area_name[] = {"csa", "sqa", "lsqa", "pvt"}; +static const char *const area_upper[] = {"CSA", "SQA", "LSQA", "PVT"}; -static void human(uint64_t n, char *buf, size_t len) -{ +/** @brief A byte count in K, M or G, whichever fits best. */ +static void human(uint64_t n, char *buf, size_t len) { if (n >= (1ULL << 30)) (void)snprintf(buf, len, "%.1fG", (double)n / (double)(1ULL << 30)); else if (n >= (1ULL << 20)) @@ -57,58 +64,47 @@ static void human(uint64_t n, char *buf, size_t len) } #if defined(__MVS__) -static void hexdump(const char *tag, const unsigned char *p, unsigned len, - unsigned max) -{ +static void hexdump(const char *tag, const unsigned char *p, unsigned int len, + unsigned int max) { + unsigned int i, j; + if (len > max) len = max; - for (unsigned i = 0; i < len; i += 16) { + for (i = 0; i < len; i += 16) { (void)fprintf(stderr, "%s %04X:", tag, i); - for (unsigned j = 0; j < 16 && i + j < len; j++) + for (j = 0; j < 16 && i + j < len; j++) (void)fprintf(stderr, " %02X", p[i + j]); (void)fputc('\n', stderr); } } static void dump_work(const struct vsm_info *v, const unsigned char *workp, - const unsigned char *data, unsigned len, int rc) -{ + const unsigned char *data, unsigned int len, int rc) { (void)fprintf(stderr, "ztop: VSMLIST %s %s rc=%d data=%08X len=%u\n", area_name[v->area - 1], v->space == VSM_UNALLOC ? "UNALLOC" : "FREE", rc, - (unsigned)(uintptr_t)data, len); + (unsigned int)(uintptr_t)data, len); hexdump("work", workp, 32, 32); if (data != NULL && len > 0) hexdump("data", data, len, 256); } -#endif - -static int pct(const struct vsm_info *v) -{ - uint64_t total; - - if (!v->unalloc_valid || v->area != VSM_CSA) - return -1; - total = v->foot + v->unalloc; - if (total == 0) - return 0; - return (int)((v->used * 100u + total / 2) / total); -} -#if defined(__MVS__) -static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) -{ +static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) { int calls = 0; + const unsigned char *data; + unsigned int len; - vsm_reset(v, (unsigned)area, (unsigned)space); - memset(work, 0, 4); /* return code must start at 0 */ + vsm_reset(v, (unsigned int)area, (unsigned int)space); + memset(work, 0, 4); /* the return code must start at 0 */ for (;;) { + struct zreq req = {0}; + bool ok; + if (++calls > 64) { (void)snprintf(v->err, sizeof v->err, "VSMLIST did not finish after 64 calls"); return false; } - struct zreq req = { 0 }; req.area = area; req.space = space; req.len = WORK_SIZE; @@ -116,12 +112,10 @@ static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) req.rc = -1; (void)zvslist(&req); if (req.rc != 0 && req.rc != 4) { - (void)snprintf(v->err, sizeof v->err, - "VSMLIST returned %d", req.rc); + (void)snprintf(v->err, sizeof v->err, "VSMLIST returned %d", + req.rc); return false; } - const unsigned char *data; - unsigned len; if (!vsm_work_data(work, WORK_SIZE, &data, &len)) { (void)snprintf(v->err, sizeof v->err, "VSMLIST work area has an unusable data pointer"); @@ -129,9 +123,8 @@ static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) } if (dump) dump_work(v, work, data, len, req.rc); - bool ok = space == VSM_UNALLOC - ? vsm_parse_unalloc(v, data, len) - : vsm_parse_alloc(v, data, len); + ok = space == VSM_UNALLOC ? vsm_parse_unalloc(v, data, len) + : vsm_parse_alloc(v, data, len); if (!ok) return false; if (req.rc == 0) @@ -140,8 +133,7 @@ static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) } } #else -static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) -{ +static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) { (void)area; (void)space; (void)dump; @@ -150,12 +142,12 @@ static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) } #endif -static bool collect_area(struct vsm_info *v, int area, bool dump) -{ +static bool collect_area(struct vsm_info *v, int area, bool dump) { if (!fetch_one(v, area, VSM_FREE, dump)) return false; if (area == VSM_CSA || area == VSM_PVT) { struct vsm_info u; + if (fetch_one(&u, area, VSM_UNALLOC, dump)) { v->unalloc = u.unalloc; v->unalloc_blocks = u.unalloc_blocks; @@ -170,15 +162,26 @@ static bool collect_area(struct vsm_info *v, int area, bool dump) return true; } -static void print_area(const struct vsm_info *v) -{ +/** @brief Fraction of the mapped area in use, or -1 when there is no total. */ +static int pct(const struct vsm_info *v) { + uint64_t total; + + if (!v->unalloc_valid || v->area != VSM_CSA) + return -1; + total = v->foot + v->unalloc; + if (total == 0) + return 0; + return (int)((v->used * 100u + total / 2) / total); +} + +static void print_area(const struct vsm_info *v) { const char *name = area_name[v->area - 1]; bool pvt = v->area == VSM_PVT; int p = pct(v); + int i; - (void)printf("area %s: used %llu free %llu mapped %llu blocks %u", - name, (unsigned long long)v->used, - (unsigned long long)v->free, + (void)printf("area %s: used %llu free %llu mapped %llu blocks %u", name, + (unsigned long long)v->used, (unsigned long long)v->free, (unsigned long long)v->foot, v->blocks); if (v->area == VSM_CSA && v->unalloc_valid) (void)printf(" unallocated %llu total %llu use %d%%", @@ -189,36 +192,34 @@ static void print_area(const struct vsm_info *v) (void)printf("\n"); if (pvt) - (void)printf("%3s %3s %8s %5s %10s %10s %10s %10s %8s\n", - "sp", "key", "tcb", "blks", "used", "free", "mapped", - "largest", "addr"); + (void)printf("%3s %3s %8s %5s %10s %10s %10s %10s %8s\n", "sp", "key", + "tcb", "blks", "used", "free", "mapped", "largest", + "addr"); else - (void)printf("%3s %3s %6s %10s %10s %10s %10s %17s\n", - "sp", "key", "blks", "used", "free", "mapped", - "largest", "address"); + (void)printf("%3s %3s %6s %10s %10s %10s %10s %17s\n", "sp", "key", + "blks", "used", "free", "mapped", "largest", "address"); - for (int i = 0; i < v->nsub; i++) { + for (i = 0; i < v->nsub; i++) { const struct vsm_subpool *s = &v->sub[i]; char addr[32]; if (s->blocks == 0) (void)snprintf(addr, sizeof addr, "-"); else if (pvt) - (void)snprintf(addr, sizeof addr, "%08X", (unsigned)s->lo); + (void)snprintf(addr, sizeof addr, "%08X", (unsigned int)s->lo); else - (void)snprintf(addr, sizeof addr, "%08X-%08X", - (unsigned)s->lo, (unsigned)s->hi); + (void)snprintf(addr, sizeof addr, "%08X-%08X", (unsigned int)s->lo, + (unsigned int)s->hi); if (pvt) (void)printf("%3u %3u %08X %5u %10llu %10llu %10llu %10llu %s\n", - s->id, s->key, (unsigned)s->tcb, s->blocks, + s->id, s->key, (unsigned int)s->tcb, s->blocks, (unsigned long long)s->used, (unsigned long long)s->free, (unsigned long long)s->foot, (unsigned long long)s->largest, addr); else - (void)printf("%3u %3u %6u %10llu %10llu %10llu %10llu %s\n", - s->id, s->key, s->blocks, - (unsigned long long)s->used, + (void)printf("%3u %3u %6u %10llu %10llu %10llu %10llu %s\n", s->id, + s->key, s->blocks, (unsigned long long)s->used, (unsigned long long)s->free, (unsigned long long)s->foot, (unsigned long long)s->largest, addr); @@ -230,251 +231,271 @@ static void print_area(const struct vsm_info *v) (void)printf("unallocated %llu bytes in %u blocks, largest %llu", (unsigned long long)v->unalloc, v->unalloc_blocks, (unsigned long long)v->largest_unalloc); - for (int i = 0; i < v->nregion && i < VSM_MAX_REGION; i++) + for (i = 0; i < v->nregion && i < VSM_MAX_REGION; i++) (void)printf("%s %08X+%08X", i == 0 ? " regions" : ",", - (unsigned)v->region[i].addr, - (unsigned)v->region[i].len); + (unsigned int)v->region[i].addr, + (unsigned int)v->region[i].len); (void)printf("\n"); } if (v->err[0] != '\0') (void)printf("warning: %s\n", v->err); } +static void print_system(const struct zsys *z) { + (void)printf( + "system %s host %s os %s machine %s address spaces %d/%u\n", + z->sysname, z->host, z->os, z->machine, z->njobs, z->slots); +} + +static void print_jobs(const struct zsys *z) { + int i; + + (void)printf("%4s %-8s %8s\n", "asid", "job", "ascb"); + for (i = 0; i < z->njobs; i++) + (void)printf("%4u %-8s %08X\n", z->job[i].asid, z->job[i].name, + (unsigned int)z->job[i].ascb); +} + struct app { struct vsm_info info[4]; bool have[4]; char err[4][160]; - int sel; - bool all; - bool paused; - bool help; + struct zsys sys; + bool have_sys; + char sys_err[160]; int interval; int collect_ms; - int scroll; - char host[80]; + bool paused; + bool help; + bool quit; + int tab; + int sub; + struct tui_table storage; + struct tui_table jobs; + struct tui_app *tapp; + char host[65]; }; -static int visible_rows(const struct tui *t) -{ - int n = t->h - 8; - return n < 1 ? 1 : n; +static const struct tui_col storage_cols[] = { + {"SP", 3, true}, {"KY", 3, true}, {"BLKS", 6, true}, + {"USED", 10, true}, {"FREE", 10, true}, {"MAPPED", 10, true}, + {"LARGEST", 10, true}, {"ADDRESS", 17, false}, +}; + +static const struct tui_col pvt_cols[] = { + {"SP", 3, true}, {"KY", 3, true}, {"BLKS", 5, true}, + {"USED", 10, true}, {"FREE", 10, true}, {"MAPPED", 10, true}, + {"LARGEST", 10, true}, {"TCB", 9, false}, +}; + +static const struct tui_col job_cols[] = { + {"ASID", 4, true}, + {"JOB", 8, false}, + {"ASCB", 10, false}, +}; + +static void storage_cell(void *ctx, int row, int col, char *buf, size_t len) { + const struct app *a = ctx; + const struct vsm_subpool *s = &a->info[a->sub].sub[row]; + char u[16], f[16], m[16], l[16]; + + switch (col) { + case 0: + (void)snprintf(buf, len, "%u", s->id); + break; + case 1: + (void)snprintf(buf, len, "%u", s->key); + break; + case 2: + (void)snprintf(buf, len, "%u", s->blocks); + break; + case 3: + human(s->used, u, sizeof u); + (void)snprintf(buf, len, "%s", u); + break; + case 4: + human(s->free, f, sizeof f); + (void)snprintf(buf, len, "%s", f); + break; + case 5: + human(s->foot, m, sizeof m); + (void)snprintf(buf, len, "%s", m); + break; + case 6: + human(s->largest, l, sizeof l); + (void)snprintf(buf, len, "%s", l); + break; + default: + if (a->sub == 3) + (void)snprintf(buf, len, "%08X", (unsigned int)s->tcb); + else if (s->blocks == 0) + (void)snprintf(buf, len, "-"); + else + (void)snprintf(buf, len, "%08X-%08X", (unsigned int)s->lo, + (unsigned int)s->hi); + break; + } +} + +static void job_cell(void *ctx, int row, int col, char *buf, size_t len) { + const struct app *a = ctx; + const struct zjob *j = &a->sys.job[row]; + + switch (col) { + case 0: + (void)snprintf(buf, len, "%u", j->asid); + break; + case 1: + (void)snprintf(buf, len, "%s", j->name); + break; + default: + (void)snprintf(buf, len, "%08X", (unsigned int)j->ascb); + break; + } +} + +static void sys_read(struct app *a) { + struct zsys z; + struct utsname u; + + (void)memcpy(&z, &a->sys, sizeof z); + if (!zsys_read(&z)) { + (void)snprintf(a->sys_err, sizeof a->sys_err, + "CVT/ASVT are only available on z/OS"); + a->have_sys = false; + return; + } + if (uname(&u) == 0) { + (void)snprintf(z.os, sizeof z.os, "%s %s", u.sysname, u.release); + (void)snprintf(z.machine, sizeof z.machine, "%s", u.machine); + } + (void)snprintf(z.host, sizeof z.host, "%s", a->host); + a->sys = z; + a->have_sys = true; + a->sys_err[0] = '\0'; } -static void collect(struct app *a) -{ +static void collect(struct app *a) { struct timespec t0, t1; - int first = a->all ? 0 : a->sel; - int last = a->all ? 3 : a->sel; + int i; (void)clock_gettime(CLOCK_MONOTONIC, &t0); - for (int i = first; i <= last; i++) { + for (i = 0; i < 4; i++) { struct vsm_info v; + if (collect_area(&v, i + 1, false)) { a->info[i] = v; a->have[i] = true; a->err[i][0] = '\0'; } else { (void)snprintf(a->err[i], sizeof a->err[i], "%s", v.err); - if (!a->have[i]) - a->info[i].area = (unsigned)(i + 1); } } + sys_read(a); (void)clock_gettime(CLOCK_MONOTONIC, &t1); a->collect_ms = (int)((t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000); } -static void draw_tabs(struct tui *t, const struct app *a) -{ - static const char *const tabs[4] = { "1 CSA", "2 SQA", "3 LSQA", "4 PVT" }; +static void draw_header(struct tui *t, const struct app *a) { + char now[16]; + time_t clock_now = time(NULL); + struct tm tm; - tui_fill(t, 0, 1, t->w, 1, ' ', TUI_PLAIN); - for (int i = 0; i < 4; i++) { - tui_style st = (!a->all && a->sel == i) ? TUI_TITLE : TUI_LABEL; - tui_printf(t, 1 + i * 9, 1, 8, st, " %s ", tabs[i]); - } - tui_printf(t, 38, 1, 7, a->all ? TUI_TITLE : TUI_LABEL, " a ALL "); + (void)localtime_r(&clock_now, &tm); + (void)strftime(now, sizeof now, "%H:%M:%S", &tm); + tui_fill(t, 0, 0, t->w, 1, ' ', TUI_TITLE); + tui_printf(t, 1, 0, t->w - 30, TUI_TITLE, " ztop %s %s %s collect %dms ", + ZTOP_VERSION, a->host, now, a->collect_ms); if (a->paused) - tui_printf(t, t->w - 8, 1, 7, TUI_WARN, " PAUSED"); -} - -static void draw_bar(struct tui *t, int x, int y, int p) -{ - char b[13]; - int fill = p < 0 ? 0 : p / 10; - - if (fill > 10) - fill = 10; - b[0] = '['; - for (int i = 0; i < 10; i++) - b[1 + i] = i < fill ? '#' : '-'; - b[11] = ']'; - b[12] = '\0'; - tui_put(t, x, y, b, 12, - p < 0 ? TUI_STYLE(7, 0, TUI_DIM) - : p < 70 ? TUI_GOOD : p < 85 ? TUI_WARN : TUI_BAD); + tui_put(t, t->w - 9, 0, " PAUSED ", 8, TUI_WARN); } -static void draw_all(struct tui *t, const struct app *a) -{ - static const int xnum = 8, xused = 15, xfree = 26, xmap = 37; - static const int xtot = 48, xpct = 59, xbar = 66; - - tui_printf(t, 1, 3, 6, TUI_LABEL, "AREA"); - tui_printf(t, xnum, 3, 6, TUI_LABEL, "BLOCKS"); - tui_printf(t, xused, 3, 9, TUI_LABEL, "USED"); - tui_printf(t, xfree, 3, 9, TUI_LABEL, "FREE"); - tui_printf(t, xmap, 3, 9, TUI_LABEL, "MAPPED"); - tui_printf(t, xtot, 3, 9, TUI_LABEL, "TOTAL"); - tui_printf(t, xpct, 3, 5, TUI_LABEL, "USE"); +static void draw_tabs(struct tui *t, const struct app *a) { + static const char *const labels[3] = {"1 STORAGE", "2 SYSTEM", "3 JOBS"}; + int x = tui_tabs_draw(t, 0, 1, labels, 3, a->tab); - for (int i = 0; i < 4; i++) { - int y = 4 + i; - const struct vsm_info *v = &a->info[i]; - char used[16], freed[16], mapped[16], total[16], pc[8]; - int p; - - if (!a->have[i]) { - tui_printf(t, 1, y, 0, TUI_BAD, "%-4s %s", area_upper[i], - a->err[i][0] ? a->err[i] : "collecting..."); - continue; - } - p = pct(v); - human(v->used, used, sizeof used); - human(v->free, freed, sizeof freed); - human(v->foot, mapped, sizeof mapped); - if (v->area == VSM_CSA && v->unalloc_valid) { - human(v->foot + v->unalloc, total, sizeof total); - (void)snprintf(pc, sizeof pc, "%d%%", p); - } else { - (void)snprintf(total, sizeof total, "-"); - (void)snprintf(pc, sizeof pc, "-"); - } - tui_printf(t, 1, y, 4, TUI_PLAIN, "%s", area_upper[i]); - tui_printf(t, xnum, y, 6, TUI_PLAIN, "%6u", v->blocks); - tui_printf(t, xused, y, 9, TUI_PLAIN, "%9s", used); - tui_printf(t, xfree, y, 9, TUI_PLAIN, "%9s", freed); - tui_printf(t, xmap, y, 9, TUI_PLAIN, "%9s", mapped); - tui_printf(t, xtot, y, 9, TUI_PLAIN, "%9s", total); - tui_printf(t, xpct, y, 5, - p < 0 ? TUI_PLAIN : p < 70 ? TUI_GOOD : - p < 85 ? TUI_WARN : TUI_BAD, "%5s", pc); - draw_bar(t, xbar, y, p); - } + tui_printf(t, x + 1, 1, t->w - x - 2, TUI_LABEL, "refresh %ds +/-", + a->interval); } -static void draw_detail(struct tui *t, struct app *a) -{ - const struct vsm_info *v = &a->info[a->sel]; - bool pvt = a->sel == 3; - int rows = visible_rows(t); +static void draw_storage(struct tui *t, struct app *a) { + const struct vsm_info *v = &a->info[a->sub]; + tui_rect r = {0, 5, t->w, t->h - 7}; + char used[16], freed[16], mapped[16], total[16], pcbuf[8]; int p = pct(v); - if (!a->have[a->sel]) { - tui_printf(t, 1, 3, 0, TUI_BAD, "%s: %s", area_upper[a->sel], - a->err[a->sel][0] ? a->err[a->sel] : "no data"); + a->storage.cols = a->sub == 3 ? pvt_cols : storage_cols; + tui_printf(t, 1, 3, 6, a->sub == 0 ? TUI_TITLE : TUI_LABEL, " CSA "); + tui_printf(t, 7, 3, 6, a->sub == 1 ? TUI_TITLE : TUI_LABEL, " SQA "); + tui_printf(t, 13, 3, 6, a->sub == 2 ? TUI_TITLE : TUI_LABEL, " LSQA "); + tui_printf(t, 20, 3, 6, a->sub == 3 ? TUI_TITLE : TUI_LABEL, " PVT "); + + if (!a->have[a->sub]) { + tui_printf(t, 1, 6, t->w - 2, TUI_BAD, "%s: %s", area_upper[a->sub], + a->err[a->sub][0] ? a->err[a->sub] : "no data"); return; } - - char used[16], freed[16], mapped[16], total[16]; human(v->used, used, sizeof used); human(v->free, freed, sizeof freed); human(v->foot, mapped, sizeof mapped); - if (v->area == VSM_CSA && v->unalloc_valid) + if (v->area == VSM_CSA && v->unalloc_valid) { human(v->foot + v->unalloc, total, sizeof total); - else - (void)snprintf(total, sizeof total, "-"); - - tui_printf(t, 1, 3, 0, TUI_PLAIN, - "%s used %s free %s mapped %s total %s %d%%", - area_upper[a->sel], used, freed, mapped, total, p); - - if (pvt) { - tui_printf(t, 1, 4, 3, TUI_LABEL, "SP"); - tui_printf(t, 5, 4, 3, TUI_LABEL, "KY"); - tui_printf(t, 9, 4, 8, TUI_LABEL, "TCB"); - tui_printf(t, 18, 4, 5, TUI_LABEL, "BLKS"); - tui_printf(t, 25, 4, 9, TUI_LABEL, "USED"); - tui_printf(t, 35, 4, 9, TUI_LABEL, "FREE"); - tui_printf(t, 45, 4, 9, TUI_LABEL, "MAPPED"); - tui_printf(t, 55, 4, 9, TUI_LABEL, "LARGEST"); - tui_printf(t, 65, 4, 9, TUI_LABEL, "ADDR"); + (void)snprintf(pcbuf, sizeof pcbuf, "%d%%", p); } else { - tui_printf(t, 1, 4, 3, TUI_LABEL, "SP"); - tui_printf(t, 5, 4, 3, TUI_LABEL, "KY"); - tui_printf(t, 9, 4, 6, TUI_LABEL, "BLKS"); - tui_printf(t, 16, 4, 9, TUI_LABEL, "USED"); - tui_printf(t, 26, 4, 9, TUI_LABEL, "FREE"); - tui_printf(t, 36, 4, 9, TUI_LABEL, "MAPPED"); - tui_printf(t, 46, 4, 9, TUI_LABEL, "LARGEST"); - tui_printf(t, 56, 4, 17, TUI_LABEL, "ADDRESS"); + (void)snprintf(total, sizeof total, "-"); + (void)snprintf(pcbuf, sizeof pcbuf, "-"); } + tui_printf(t, 1, 4, t->w - 2, TUI_PLAIN, + "used %s free %s mapped %s total %s use %s blocks %u", used, + freed, mapped, total, pcbuf, v->blocks); + tui_table_draw(t, r, &a->storage, v->nsub, storage_cell, NULL, a); - if (a->scroll > v->nsub - rows) - a->scroll = v->nsub - rows; - if (a->scroll < 0) - a->scroll = 0; + if (a->err[a->sub][0] != '\0') + tui_printf(t, 1, t->h - 2, t->w - 2, TUI_BAD, "! %s", a->err[a->sub]); + else if (v->unalloc_valid) + tui_printf(t, 1, t->h - 2, t->w - 2, TUI_LABEL, + "unallocated %llu in %u blocks, largest %llu", + (unsigned long long)v->unalloc, v->unalloc_blocks, + (unsigned long long)v->largest_unalloc); +} - for (int r = 0; r < rows && a->scroll + r < v->nsub; r++) { - const struct vsm_subpool *s = &v->sub[a->scroll + r]; - int y = 5 + r; - char u[16], f[16], m[16], l[16], addr[32]; +static void draw_system(struct tui *t, const struct app *a) { + const struct zsys *z = &a->sys; - human(s->used, u, sizeof u); - human(s->free, f, sizeof f); - human(s->foot, m, sizeof m); - human(s->largest, l, sizeof l); - if (s->blocks == 0) - (void)snprintf(addr, sizeof addr, "-"); - else if (pvt) - (void)snprintf(addr, sizeof addr, "%08X", (unsigned)s->lo); - else - (void)snprintf(addr, sizeof addr, "%08X-%08X", - (unsigned)s->lo, (unsigned)s->hi); - - tui_printf(t, 1, y, 3, TUI_PLAIN, "%3u", s->id); - tui_printf(t, 5, y, 3, TUI_PLAIN, "%3u", s->key); - if (pvt) { - tui_printf(t, 9, y, 8, TUI_LABEL, "%08X", (unsigned)s->tcb); - tui_printf(t, 18, y, 5, TUI_PLAIN, "%5u", s->blocks); - tui_printf(t, 25, y, 9, TUI_PLAIN, "%9s", u); - tui_printf(t, 35, y, 9, TUI_PLAIN, "%9s", f); - tui_printf(t, 45, y, 9, TUI_PLAIN, "%9s", m); - tui_printf(t, 55, y, 9, TUI_PLAIN, "%9s", l); - tui_printf(t, 65, y, 8, TUI_LABEL, "%s", addr); - } else { - tui_printf(t, 9, y, 6, TUI_PLAIN, "%6u", s->blocks); - tui_printf(t, 16, y, 9, TUI_PLAIN, "%9s", u); - tui_printf(t, 26, y, 9, TUI_PLAIN, "%9s", f); - tui_printf(t, 36, y, 9, TUI_PLAIN, "%9s", m); - tui_printf(t, 46, y, 9, TUI_PLAIN, "%9s", l); - tui_printf(t, 56, y, 17, TUI_LABEL, "%s", addr); - } + if (!a->have_sys) { + tui_printf(t, 1, 4, t->w - 2, TUI_BAD, "%s", a->sys_err); + return; } + tui_printf(t, 1, 4, t->w - 2, TUI_LABEL, "system %s", z->sysname); + tui_printf(t, 1, 5, t->w - 2, TUI_PLAIN, "host %s", z->host); + tui_printf(t, 1, 6, t->w - 2, TUI_PLAIN, "os %s", z->os); + tui_printf(t, 1, 7, t->w - 2, TUI_PLAIN, "machine %s", z->machine); + tui_printf(t, 1, 8, t->w - 2, TUI_PLAIN, "spaces %d used, %u slots", + z->njobs, z->slots); + tui_printf( + t, 1, 10, t->w - 2, TUI_LABEL, + "storage CSA %llu unallocated, PVT %llu", + (unsigned long long)(a->info[0].unalloc_valid ? a->info[0].unalloc : 0), + (unsigned long long)(a->info[3].unalloc_valid ? a->info[3].unalloc + : 0)); +} - /* The line above the keys: first an error, then regions. */ - int y = t->h - 3; - if (a->err[a->sel][0] != '\0') - tui_printf(t, 1, y, t->w - 2, TUI_BAD, "! %s", a->err[a->sel]); - else if (v->unalloc_valid) { - if (v->nregion > 0) { - tui_printf(t, 1, y, t->w - 2, TUI_LABEL, - "regions: %08X+%08X%s", (unsigned)v->region[0].addr, - (unsigned)v->region[0].len, - v->nregion > 1 ? " ..." : ""); - } else { - tui_printf(t, 1, y, t->w - 2, TUI_PLAIN, - "unallocated %llu bytes, %u blocks, largest %llu", - (unsigned long long)v->unalloc, v->unalloc_blocks, - (unsigned long long)v->largest_unalloc); - } +static void draw_jobs(struct tui *t, struct app *a) { + tui_rect r = {0, 3, t->w, t->h - 5}; + + if (!a->have_sys) { + tui_printf(t, 1, 4, t->w - 2, TUI_BAD, "%s", a->sys_err); + return; } + tui_table_draw(t, r, &a->jobs, a->sys.njobs, job_cell, NULL, a); + tui_printf(t, 1, t->h - 2, t->w - 2, TUI_LABEL, + "%d address spaces, %u slots", a->sys.njobs, a->sys.slots); } -static void draw_help(struct tui *t) -{ +static void draw_help(struct tui *t) { int w = t->w < 56 ? t->w - 2 : 54; - int h = 15; + int h = 16; int x = (t->w - w) / 2; int y = (t->h - h) / 2; @@ -482,63 +503,49 @@ static void draw_help(struct tui *t) tui_box(t, x, y, w, h, TUI_LABEL); tui_printf(t, x + 2, y + 1, w - 4, TUI_TITLE, "ztop keys"); tui_printf(t, x + 2, y + 3, w - 4, TUI_PLAIN, "q quit"); - tui_printf(t, x + 2, y + 4, w - 4, TUI_PLAIN, "1-4 csa, sqa, lsqa, pvt"); - tui_printf(t, x + 2, y + 5, w - 4, TUI_PLAIN, "a all areas"); - tui_printf(t, x + 2, y + 6, w - 4, TUI_PLAIN, "p pause refresh"); - tui_printf(t, x + 2, y + 7, w - 4, TUI_PLAIN, "r refresh now"); - tui_printf(t, x + 2, y + 8, w - 4, TUI_PLAIN, "+ - interval up / down"); - tui_printf(t, x + 2, y + 9, w - 4, TUI_PLAIN, "j k scroll subpools"); - tui_printf(t, x + 2, y + 10, w - 4, TUI_PLAIN, "up dn same"); - tui_printf(t, x + 2, y + 11, w - 4, TUI_PLAIN, "g G first / last"); - tui_printf(t, x + 2, y + 12, w - 4, TUI_PLAIN, "? close help"); + tui_printf(t, x + 2, y + 4, w - 4, TUI_PLAIN, "TAB next view"); + tui_printf(t, x + 2, y + 5, w - 4, TUI_PLAIN, + "1-3 storage, system, jobs"); + tui_printf(t, x + 2, y + 6, w - 4, TUI_PLAIN, "1-4 CSA, SQA, LSQA, PVT"); + tui_printf(t, x + 2, y + 7, w - 4, TUI_PLAIN, "p pause refresh"); + tui_printf(t, x + 2, y + 8, w - 4, TUI_PLAIN, "r refresh now"); + tui_printf(t, x + 2, y + 9, w - 4, TUI_PLAIN, "+ - interval up / down"); + tui_printf(t, x + 2, y + 10, w - 4, TUI_PLAIN, "j k move the selection"); + tui_printf(t, x + 2, y + 11, w - 4, TUI_PLAIN, "up dn same"); + tui_printf(t, x + 2, y + 12, w - 4, TUI_PLAIN, "g G first / last"); + tui_printf(t, x + 2, y + 13, w - 4, TUI_PLAIN, "? close help"); + tui_printf(t, x + 2, y + 14, w - 4, TUI_PLAIN, "1-4 inside storage"); } -static void draw(struct tui *t, struct app *a) -{ - char now[16]; - time_t clock_now = time(NULL); - struct tm tm; +static void view(void *model, struct tui *t) { + struct app *a = model; tui_clear(t); - (void)localtime_r(&clock_now, &tm); - (void)strftime(now, sizeof now, "%H:%M:%S", &tm); - - tui_fill(t, 0, 0, t->w, 1, ' ', TUI_TITLE); - tui_printf(t, 1, 0, t->w - 12, TUI_TITLE, - " ztop %s %s %s refresh %ds collect %dms ", - ZTOP_VERSION, a->host, now, a->interval, a->collect_ms); + draw_header(t, a); draw_tabs(t, a); tui_fill(t, 0, 2, t->w, 1, '-', TUI_STYLE(7, 0, TUI_DIM)); if (t->w < 70 || t->h < 14) { tui_printf(t, 1, 3, 0, TUI_BAD, "terminal too small: need 70x14"); - } else if (a->all) { - draw_all(t, a); - tui_printf(t, 1, 9, 0, TUI_PLAIN, - "unallocated: CSA %llu PVT %llu", - (unsigned long long)(a->info[0].unalloc_valid - ? a->info[0].unalloc : 0), - (unsigned long long)(a->info[3].unalloc_valid - ? a->info[3].unalloc : 0)); + } else if (a->tab == 0) { + draw_storage(t, a); + } else if (a->tab == 1) { + draw_system(t, a); } else { - draw_detail(t, a); + draw_jobs(t, a); } - if (a->help) draw_help(t); - - tui_fill(t, 0, t->h - 1, t->w, 1, ' ', TUI_TITLE); - tui_printf(t, 1, t->h - 1, t->w - 2, TUI_TITLE, - "q quit 1-4 area a all p pause r refresh +/- %ds ? help", - a->interval); + tui_statusbar(t, "q quit TAB view j/k move r refresh p pause ? help", + a->paused ? "PAUSED" : ""); } -static bool parse_areas(const char *s, unsigned *mask) -{ - unsigned m = 0; +static bool parse_areas(const char *s, unsigned int *mask) { + unsigned int m = 0; while (*s != '\0') { size_t n = strcspn(s, ","); + if (n == 3 && strncmp(s, "csa", 3) == 0) m |= 1u << 0; else if (n == 3 && strncmp(s, "sqa", 3) == 0) @@ -559,154 +566,196 @@ static bool parse_areas(const char *s, unsigned *mask) return m != 0; } -static void usage(FILE *f) -{ - (void)fprintf(f, - "usage: ztop [-a csa|sqa|lsqa|pvt|all] [-x] [-d [seconds]] [-h]\n" - " -a area to report (default csa); comma-separate areas or use all\n" +static void usage(FILE *f) { + (void)fprintf( + f, + "usage: ztop [-a csa|sqa|lsqa|pvt|all] [-s] [-j] [-x] [-d [seconds]]\n" + " -a storage areas to report (default csa); comma-separate or all\n" + " -s system name, host, release and address-space count\n" + " -j one line per address space\n" " -x dump the VSMLIST work and data areas (one-shot only)\n" - " -d interactive full-screen view, refreshed every 2 seconds\n" + " -d interactive view, refreshed every 2 seconds by default\n" " -h this text\n"); } -static void run_oneshot(unsigned mask, bool dump) -{ - int rc = 0; +static bool update(void *model, const struct tui_msg *m) { + struct app *a = model; + int rows, height; - for (int i = 0; i < 4; i++) { - if ((mask & (1u << i)) == 0) - continue; - struct vsm_info v; - if (!collect_area(&v, i + 1, dump)) { - (void)fprintf(stderr, "ztop: %s: %s\n", area_name[i], v.err); - rc = 1; - continue; - } - if (i != 0) - (void)printf("\n"); - print_area(&v); + if (a->help) { + if (m->type == TUI_MSG_KEY && (m->key == '?' || m->key == TUI_KEY_ESC || + m->key == 'q' || m->key == 0x03)) + a->help = false; + return true; } - exit(rc); + if (m->type == TUI_MSG_TICK) { + if (!a->paused) + collect(a); + return true; + } + if (m->type == TUI_MSG_RESIZE) + return true; + if (m->type != TUI_MSG_KEY) + return false; + + if (m->key == 'q' || m->key == TUI_KEY_ESC || m->key == 0x03) { + a->quit = true; + return false; + } + if (m->key == '?') { + a->help = true; + return true; + } + if (m->key == 'p') { + a->paused = !a->paused; + return true; + } + if (m->key == 'r') { + collect(a); + return true; + } + if (m->key == '+' || m->key == '=') { + if (a->interval < 60) + a->interval++; + a->tapp->tick_ms = a->interval * 1000; + return true; + } + if (m->key == '-' && a->interval > 1) { + a->interval--; + a->tapp->tick_ms = a->interval * 1000; + return true; + } + if (m->key == TUI_KEY_TAB) { + a->tab = (a->tab + 1) % 3; + return true; + } + if (m->key == TUI_KEY_BACKTAB) { + a->tab = (a->tab + 2) % 3; + return true; + } + if (a->tab == 0 && m->key >= '1' && m->key <= '4') { + a->sub = m->key - '1'; + return true; + } + + rows = a->tab == 0 ? a->info[a->sub].nsub : a->sys.njobs; + height = a->tab == 0 ? m->h - 8 : m->h - 6; + if (height < 1) + height = 1; + if (a->tab == 0) + return tui_viewport_key(&a->storage.vp, m->key, rows, height); + if (a->tab == 2) + return tui_viewport_key(&a->jobs.vp, m->key, rows, height); + return false; +} + +static void sys_fill(struct zsys *z, const char *host) { + struct utsname u; + + if (uname(&u) == 0) { + (void)snprintf(z->os, sizeof z->os, "%s %s", u.sysname, u.release); + (void)snprintf(z->machine, sizeof z->machine, "%s", u.machine); + } + (void)snprintf(z->host, sizeof z->host, "%s", host); } -static void run_tui(unsigned mask, int interval) -{ +static void run_tui(int interval) { static struct app a; struct tui t; + struct tui_app ta; memset(&a, 0, sizeof a); - a.interval = interval; - a.all = (mask & 0xFu) == 0xFu; - for (int i = 0; i < 4; i++) { - a.info[i].area = (unsigned)(i + 1); - if (!a.all && (mask & (1u << i)) != 0 && a.sel == 0) - a.sel = i; - } if (gethostname(a.host, sizeof a.host - 1) != 0) (void)snprintf(a.host, sizeof a.host, "?"); - a.host[sizeof a.host - 1] = '\0'; + a.interval = interval; + a.storage.cols = storage_cols; + a.storage.ncols = 8; + a.jobs.cols = job_cols; + a.jobs.ncols = 3; if (!tui_open(&t)) { (void)fprintf(stderr, "ztop: -d needs a terminal\n"); exit(1); } collect(&a); - for (;;) { - draw(&t, &a); - tui_flush(&t); - int k = tui_key(&t, a.paused ? -1 : a.interval * 1000); - if (k == TUI_KEY_NONE) { - collect(&a); - continue; - } - if (k == TUI_KEY_RESIZE) { - (void)tui_resize(&t); - continue; - } - if (a.help) { - if (k == '?' || k == TUI_KEY_ESC) - a.help = false; - else if (k == 'q') - break; - continue; - } - if (k == 'q' || k == 0x03 || k == TUI_KEY_ESC) - break; - if (k >= '1' && k <= '4') { - a.sel = k - '1'; - a.all = false; - a.scroll = 0; - collect(&a); - continue; - } - if (k == 'a') { - a.all = !a.all; - collect(&a); - continue; - } - if (k == 'p') { - a.paused = !a.paused; - continue; - } - if (k == 'r') { - collect(&a); - continue; - } - if (k == '+' || k == '=') { - if (a.interval < 60) - a.interval++; - continue; - } - if (k == '-') { - if (a.interval > 1) - a.interval--; + memset(&ta, 0, sizeof ta); + ta.model = &a; + ta.update = update; + ta.view = view; + ta.tick_ms = interval * 1000; + a.tapp = &ta; + tui_run(&t, &ta); + tui_close(&t); +} + +static void run_oneshot(unsigned mask, bool want_sys, bool want_jobs, + bool dump) { + char host[65]; + bool printed = false; + int rc = 0; + int i; + + for (i = 0; i < 4; i++) { + struct vsm_info v; + + if ((mask & (1u << i)) == 0) continue; - } - if (k == '?') { - a.help = true; + if (!collect_area(&v, i + 1, dump)) { + (void)fprintf(stderr, "ztop: %s: %s\n", area_name[i], v.err); + rc = 1; continue; } - int rows = visible_rows(&t); - int max = a.info[a.sel].nsub - rows; - if (max < 0) - max = 0; - if (k == 'j' || k == TUI_KEY_DOWN) { - if (a.scroll < max) - a.scroll++; - } else if (k == 'k' || k == TUI_KEY_UP) { - if (a.scroll > 0) - a.scroll--; - } else if (k == TUI_KEY_PGDN) { - a.scroll += rows; - if (a.scroll > max) - a.scroll = max; - } else if (k == TUI_KEY_PGUP) { - a.scroll -= rows; - if (a.scroll < 0) - a.scroll = 0; - } else if (k == 'g' || k == TUI_KEY_HOME) { - a.scroll = 0; - } else if (k == 'G' || k == TUI_KEY_END) { - a.scroll = max; + if (printed) + (void)printf("\n"); + print_area(&v); + printed = true; + } + if (want_sys || want_jobs) { + struct zsys z; + + if (gethostname(host, sizeof host - 1) != 0) + (void)snprintf(host, sizeof host, "?"); + host[sizeof host - 1] = '\0'; + if (!zsys_read(&z)) { + (void)fprintf(stderr, + "ztop: system and jobs are only available on z/OS\n"); + rc = 1; + } else { + sys_fill(&z, host); + if (printed) + (void)printf("\n"); + if (want_sys) + print_system(&z); + if (want_jobs) { + if (want_sys) + (void)printf("\n"); + print_jobs(&z); + } } } - tui_close(&t); + exit(rc); } -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { unsigned mask = 0; bool dump = false; bool interactive = false; + bool want_sys = false; + bool want_jobs = false; int interval = 0; + int i; - for (int i = 1; i < argc; i++) { + for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { usage(stdout); return 0; } else if (strcmp(argv[i], "-x") == 0) { dump = true; + } else if (strcmp(argv[i], "-s") == 0) { + want_sys = true; + } else if (strcmp(argv[i], "-j") == 0) { + want_jobs = true; } else if (strcmp(argv[i], "-a") == 0) { if (i + 1 >= argc || !parse_areas(argv[++i], &mask)) { usage(stderr); @@ -726,8 +775,6 @@ int main(int argc, char **argv) return 2; } } - if (mask == 0) - mask = 1u; if (interactive) { if (dump) @@ -736,9 +783,11 @@ int main(int argc, char **argv) interval = 2; if (interval > 60) interval = 60; - run_tui(mask, interval); + run_tui(interval); } else { - run_oneshot(mask, dump); + if (mask == 0 && !want_sys && !want_jobs) + mask = 1u; + run_oneshot(mask, want_sys, want_jobs, dump); } return 0; } diff --git a/tests/test_vsm.c b/tests/test_vsm.c index 0d8d358..371b7ad 100644 --- a/tests/test_vsm.c +++ b/tests/test_vsm.c @@ -9,22 +9,19 @@ static unsigned char buf[8192]; static unsigned len; -static void put8(unsigned v) -{ +static void put8(unsigned v) { if (len < sizeof buf) buf[len++] = (unsigned char)v; } -static void put32(uint32_t v) -{ +static void put32(uint32_t v) { put8(v >> 24); put8(v >> 16); put8(v >> 8); put8(v); } -static void desc(unsigned id, unsigned flags, uint32_t tcb, unsigned dlen) -{ +static void desc(unsigned id, unsigned flags, uint32_t tcb, unsigned dlen) { put8(0); put8(dlen); put8(id); @@ -34,22 +31,23 @@ static void desc(unsigned id, unsigned flags, uint32_t tcb, unsigned dlen) put8(0); } -static void block(uint32_t addr, uint32_t blen) -{ +static void block(uint32_t addr, uint32_t blen) { put32(addr); put32(blen); } -static int fail_line(int line, const char *what) -{ +static int fail_line(int line, const char *what) { (void)fprintf(stderr, "test_vsm.c:%d: %s\n", line, what); return 1; } -#define CHECK(c) do { if (!(c)) return fail_line(__LINE__, #c); } while (0) +#define CHECK(c) \ + do { \ + if (!(c)) \ + return fail_line(__LINE__, #c); \ + } while (0) -static int test_csa(void) -{ +static int test_csa(void) { struct vsm_info v; len = 0; @@ -90,8 +88,7 @@ static int test_csa(void) return 0; } -static int test_merge(void) -{ +static int test_merge(void) { struct vsm_info v; len = 0; @@ -111,8 +108,7 @@ static int test_merge(void) return 0; } -static int test_pvt(void) -{ +static int test_pvt(void) { struct vsm_info v; len = 0; @@ -134,8 +130,7 @@ static int test_pvt(void) return 0; } -static int test_unalloc(void) -{ +static int test_unalloc(void) { struct vsm_info v; len = 0; @@ -161,8 +156,7 @@ static int test_unalloc(void) return 0; } -static int test_bad(void) -{ +static int test_bad(void) { struct vsm_info v; /* descriptor length below the documented minimum */ @@ -214,8 +208,7 @@ static int test_bad(void) return 0; } -int main(void) -{ +int main(void) { int rc = 0; rc |= test_csa(); diff --git a/tui/Makefile b/tui/Makefile new file mode 100644 index 0000000..7304500 --- /dev/null +++ b/tui/Makefile @@ -0,0 +1,38 @@ +# libtui - a cell-buffer terminal UI with no ncurses. +# +# shellcheck disable=SC2283,SC2068 +# ^ our linter reads this as shell: `NAME = value` and `$(CFLAGS)` are make. +# +# make build libtui.a +# make demo build the demo (a terminal is needed to run it) +# make test build and run the buffer tests +# make clean +# +# On z/OS: make CC=ibm-clang. The library itself is portable POSIX; the +# z/OS specifics (EBCDIC literals, the ESC byte) are all inside tui.c. +.POSIX: +.SUFFIXES: + +CC = cc +CFLAGS = -std=c17 -O2 -Wall -Wextra -Wshadow -Wpedantic \ + -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L +AR = ar + +all: libtui.a + +libtui.a: tui.o + rm -f $@ + $(AR) rcs $@ tui.o + +tui.o: tui.c tui.h + $(CC) $(CFLAGS) -c -o $@ tui.c + +demo: demo.c libtui.a + $(CC) $(CFLAGS) -o $@ demo.c libtui.a + +test: test_tui.c libtui.a + $(CC) $(CFLAGS) -o test_tui test_tui.c libtui.a + ./test_tui + +clean: + rm -f tui.o libtui.a demo test_tui diff --git a/tests/demo_tui.c b/tui/demo.c index 1e9ad1f..6e2e081 100644 --- a/tests/demo_tui.c +++ b/tui/demo.c @@ -3,10 +3,9 @@ #include <stdio.h> #include <string.h> -#include "../src/tui.h" +#include "tui.h" -int main(void) -{ +int main(void) { struct tui t; int x = 4; diff --git a/tui/test_tui.c b/tui/test_tui.c new file mode 100644 index 0000000..63a5e86 --- /dev/null +++ b/tui/test_tui.c @@ -0,0 +1,161 @@ +/* Buffer-level tests for libtui: no terminal, no clock, no signals. + * `make test` builds and runs this next to the library. */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "tui.h" + +static int fails; + +#define CHECK(c) \ + do { \ + if (!(c)) { \ + (void)printf("FAIL line %d: %s\n", __LINE__, #c); \ + fails++; \ + } \ + } while (0) + +static unsigned char cell(const struct tui *t, int x, int y) { + return t->cur[(size_t)y * (size_t)t->w + (size_t)x].ch; +} + +static void test_buffer(void) { + struct tui t; + + memset(&t, 0, sizeof t); + CHECK(tui_alloc(&t, 20, 6)); + tui_fill(&t, 0, 0, 20, 6, ' ', TUI_PLAIN); + CHECK(cell(&t, 0, 0) == ' '); + + tui_put(&t, 18, 0, "abc", 5, TUI_PLAIN); + CHECK(cell(&t, 18, 0) == 'a'); + CHECK(cell(&t, 19, 0) == 'b'); + + tui_printf(&t, 2, 1, 3, TUI_PLAIN, "%d", 12345); + CHECK(cell(&t, 2, 1) == '1'); + CHECK(cell(&t, 4, 1) == '3'); + CHECK(cell(&t, 5, 1) == ' '); + + tui_fill(&t, -3, -3, 5, 5, 'x', TUI_PLAIN); + CHECK(cell(&t, 0, 0) == 'x'); + CHECK(cell(&t, 1, 0) == 'x'); + CHECK(cell(&t, 2, 0) == ' '); + + tui_rule(&t, 5, '-', TUI_PLAIN); + CHECK(cell(&t, 0, 5) == '-'); + CHECK(cell(&t, 19, 5) == '-'); + + tui_box(&t, 0, 2, 10, 3, TUI_PLAIN); + CHECK(cell(&t, 0, 2) == '+'); + CHECK(cell(&t, 9, 2) == '+'); + + free(t.cur); + free(t.old); +} + +static void test_viewport(void) { + struct tui_viewport v = {0, 0}; + + tui_viewport_clamp(&v, 10, 3); + CHECK(v.sel == 0 && v.top == 0); + tui_viewport_move(&v, 5, 10, 3); + CHECK(v.sel == 5 && v.top == 3); + tui_viewport_move(&v, -100, 10, 3); + CHECK(v.sel == 0 && v.top == 0); + CHECK(tui_viewport_key(&v, TUI_KEY_END, 10, 3)); + CHECK(v.sel == 9 && v.top == 7); + CHECK(tui_viewport_key(&v, TUI_KEY_PGUP, 10, 3)); + CHECK(v.sel == 6 && v.top == 6); + CHECK(!tui_viewport_key(&v, 'z', 10, 3)); + /* empty list must not go negative */ + v.sel = 3; + tui_viewport_clamp(&v, 0, 4); + CHECK(v.sel == 0 && v.top == 0); +} + +static void test_tabs(void) { + int act = 0; + + CHECK(tui_tabs_key(TUI_KEY_TAB, &act, 3)); + CHECK(act == 1); + CHECK(tui_tabs_key(TUI_KEY_BACKTAB, &act, 3)); + CHECK(act == 0); + CHECK(tui_tabs_key(TUI_KEY_LEFT, &act, 3)); + CHECK(act == 2); + CHECK(!tui_tabs_key('x', &act, 3)); + + struct tui t; + + memset(&t, 0, sizeof t); + CHECK(tui_alloc(&t, 30, 2)); + static const char *const labels[3] = {"one", "two", "three"}; + int x = tui_tabs_draw(&t, 0, 0, labels, 3, 1); + CHECK(x == 5 + 1 + 5 + 1 + 7); + CHECK(cell(&t, 0, 0) == ' '); + CHECK(cell(&t, 1, 0) == 'o'); + CHECK(cell(&t, 6, 0) == ' '); + CHECK(cell(&t, 7, 0) == 't'); + free(t.cur); + free(t.old); +} + +static void test_input(void) { + struct tui_input in; + + memset(&in, 0, sizeof in); + in.focus = true; + CHECK(tui_input_key(&in, 'a')); + CHECK(tui_input_key(&in, 'b')); + CHECK(strcmp(in.buf, "ab") == 0 && in.len == 2 && in.pos == 2); + CHECK(tui_input_key(&in, TUI_KEY_LEFT)); + CHECK(tui_input_key(&in, 'X')); + CHECK(strcmp(in.buf, "aXb") == 0 && in.pos == 2); + CHECK(tui_input_key(&in, TUI_KEY_DEL)); + CHECK(strcmp(in.buf, "aX") == 0 && in.pos == 2); + CHECK(tui_input_key(&in, TUI_KEY_BACKTAB) == false); + CHECK(tui_input_key(&in, 8)); + CHECK(strcmp(in.buf, "a") == 0 && in.pos == 1); + CHECK(tui_input_key(&in, TUI_KEY_END)); + CHECK(in.pos == 1); + in.focus = false; + CHECK(!tui_input_key(&in, 'z')); +} + +/* Rows come from a callback; check the table maps row/col and clips. */ +static void called(void *ctx, int row, int col, char *buf, size_t len) { + (void)ctx; + (void)snprintf(buf, len, "r%dc%d", row, col); +} + +static void test_table(void) { + static const struct tui_col cols[2] = { + {"A", 5, false}, + {"B", 4, true}, + }; + struct tui_table tb = {cols, 2, {0, 0}}; + struct tui t; + + memset(&t, 0, sizeof t); + CHECK(tui_alloc(&t, 20, 5)); + tui_table_draw(&t, (tui_rect){0, 0, 20, 5}, &tb, 3, called, NULL, NULL); + CHECK(cell(&t, 0, 0) == 'A'); + CHECK(cell(&t, 6, 0) == ' '); + CHECK(cell(&t, 6, 1) == 'r'); /* first data row, first column */ + CHECK(cell(&t, 8, 1) == 'c'); + tb.vp.sel = 2; + tui_table_draw(&t, (tui_rect){0, 0, 20, 5}, &tb, 3, called, NULL, NULL); + CHECK(cell(&t, 6, 3) == 'r'); /* third row is last visible */ + free(t.cur); + free(t.old); +} + +int main(void) { + test_buffer(); + test_viewport(); + test_tabs(); + test_input(); + test_table(); + (void)printf("test_tui: %s\n", fails == 0 ? "ok" : "FAILED"); + return fails != 0; +} diff --git a/tui/tui.c b/tui/tui.c new file mode 100644 index 0000000..62878d4 --- /dev/null +++ b/tui/tui.c @@ -0,0 +1,885 @@ +/** + * @file tui.c + * @brief See tui.h. One output buffer per frame, one diff against the last. + */ +#include "tui.h" + +#include <errno.h> +#include <signal.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/select.h> +#include <unistd.h> + +#ifdef __MVS__ +#define ESCS "\x27" /* EBCDIC ESC; the tty converts it to 0x1b */ +#define ESC_CHAR 0x27u /* what a key press of ESC looks like here */ +#else +#define ESCS "\x1b" +#define ESC_CHAR 0x1bu +#endif + +#define ALT_ON ESCS "[?1049h" +#define ALT_OFF ESCS "[?1049l" +#define CUR_OFF ESCS "[?25l" +#define CUR_ON ESCS "[?25h" +#define CLEAR ESCS "[H" ESCS "[2J" +#define RESET ESCS "[0m" + +static struct tui *g_tui; +static volatile sig_atomic_t g_winch; + +static void wr(int fd, const void *buf, size_t n) { + const char *p = buf; + + while (n > 0) { + ssize_t k = write(fd, p, n); + if (k < 0 && errno == EINTR) + continue; + if (k <= 0) + return; + p += (size_t)k; + n -= (size_t)k; + } +} + +static void restore(struct tui *t) { + if (!t->open) + return; + wr(t->fd_out, RESET CUR_ON ALT_OFF, strlen(RESET CUR_ON ALT_OFF)); + (void)tcsetattr(t->fd_in, TCSANOW, &t->orig); +} + +static void on_winch(int sig) { + (void)sig; + g_winch = 1; +} + +static void on_term(int sig) { + if (g_tui != NULL) + restore(g_tui); + _exit(128 + sig); +} + +static void out_flush(struct tui *t) { + if (t->olen > 0) { + wr(t->fd_out, t->out, (size_t)t->olen); + t->olen = 0; + } +} + +static void out(struct tui *t, const char *s, size_t n) { + if (t->olen + (int)n > (int)sizeof t->out) + out_flush(t); + if (n > sizeof t->out) { + wr(t->fd_out, s, n); + return; + } + memcpy(t->out + t->olen, s, n); + t->olen += (int)n; +} + +static void outs(struct tui *t, const char *s) { + out(t, s, strlen(s)); +} + +static void outf(struct tui *t, const char *fmt, ...) { + char b[64]; + va_list ap; + int n; + + va_start(ap, fmt); + n = vsnprintf(b, sizeof b, fmt, ap); + va_end(ap); + if (n > 0) + out(t, b, (size_t)n < sizeof b ? (size_t)n : sizeof b - 1); +} + +static void sgr(struct tui *t, int fg, int bg, int attr) { + char b[40]; + int n = snprintf(b, sizeof b, "%s[0", ESCS); + + if (attr & TUI_BOLD) + n += snprintf(b + n, sizeof b - (size_t)n, ";1"); + if (attr & TUI_DIM) + n += snprintf(b + n, sizeof b - (size_t)n, ";2"); + if (attr & TUI_UNDERLINE) + n += snprintf(b + n, sizeof b - (size_t)n, ";4"); + if (attr & TUI_REVERSE) + n += snprintf(b + n, sizeof b - (size_t)n, ";7"); + n += snprintf(b + n, sizeof b - (size_t)n, ";3%d;4%dm", fg, bg); + out(t, b, (size_t)n); +} + +/* Ask the terminal where the cursor is; its answer is the only size z/OS + * gives us. Returns false if the terminal does not answer. */ +static bool cpr_size(int in, int outfd, int *w, int *h) { + unsigned char b[64]; + int n = 0; + bool got = false, esc = false, csi = false; + int vals[2] = {0, 0}, nv = 0, v = 0; + + wr(outfd, ESCS "[6n", sizeof ESCS "[6n" - 1); + for (int rounds = 0; rounds < 30 && !got; rounds++) { + fd_set f; + struct timeval tv = {0, 10000}; + + FD_ZERO(&f); + FD_SET(in, &f); + int r = select(in + 1, &f, NULL, NULL, &tv); + if (r < 0 && errno == EINTR) + continue; + if (r <= 0) + continue; + ssize_t k = read(in, b + n, sizeof b - (size_t)n); + if (k <= 0) + continue; + for (ssize_t i = 0; i < k; i++) { + unsigned char c = b[n + (size_t)i]; + if (!esc) { + if (c == ESC_CHAR) + esc = true; + continue; + } + if (!csi) { + if (c == '[') + csi = true; + else if (c != ESC_CHAR) + esc = false; + continue; + } + if (c >= '0' && c <= '9') { + v = v * 10 + (c - '0'); + } else if (c == ';' && nv == 0) { + vals[nv++] = v; + v = 0; + } else if (c == 'R') { + vals[nv++] = v; + got = true; + break; + } else { + esc = csi = false; + nv = v = 0; + } + } + n = 0; + } + if (!got || nv < 2 || vals[0] <= 0 || vals[1] <= 0) + return false; + *h = vals[0]; + *w = vals[1]; + return true; +} + +static void probe_size(struct tui *t, int *w, int *h) { + struct winsize ws; + + *w = 80; + *h = 24; + if (ioctl(t->fd_out, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0 && + ws.ws_row > 0) { + *w = ws.ws_col; + *h = ws.ws_row; + } else if (!cpr_size(t->fd_in, t->fd_out, w, h)) { + const char *c = getenv("COLUMNS"); + const char *l = getenv("LINES"); + if (c != NULL && atoi(c) > 0) + *w = atoi(c); + if (l != NULL && atoi(l) > 0) + *h = atoi(l); + } + if (*w > TUI_MAX_W) + *w = TUI_MAX_W; + if (*h > TUI_MAX_H) + *h = TUI_MAX_H; + if (*w < 20) + *w = 80; + if (*h < 5) + *h = 24; +} + +bool tui_alloc(struct tui *t, int w, int h) { + struct tui_cell *cur, *old; + + if (w < 2) + w = 2; + if (h < 2) + h = 2; + if (w > TUI_MAX_W) + w = TUI_MAX_W; + if (h > TUI_MAX_H) + h = TUI_MAX_H; + cur = calloc((size_t)w * (size_t)h, sizeof *cur); + old = calloc((size_t)w * (size_t)h, sizeof *old); + if (cur == NULL || old == NULL) { + free(cur); + free(old); + return false; + } + free(t->cur); + free(t->old); + t->cur = cur; + t->old = old; + t->w = w; + t->h = h; + t->full = true; + tui_clear(t); + return true; +} + +bool tui_resize(struct tui *t) { + int w, h; + + probe_size(t, &w, &h); + if (w == t->w && h == t->h) + return false; + return tui_alloc(t, w, h); +} + +bool tui_open(struct tui *t) { + struct termios r; + + memset(t, 0, sizeof *t); + t->fd_in = 0; + t->fd_out = 1; + if (!isatty(t->fd_in) || !isatty(t->fd_out)) + return false; + if (tcgetattr(t->fd_in, &t->orig) != 0) + return false; + r = t->orig; + r.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ISIG | IEXTEN); + r.c_iflag &= (tcflag_t) ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP); + r.c_oflag &= (tcflag_t)~OPOST; + r.c_cc[VMIN] = 0; + r.c_cc[VTIME] = 0; + if (tcsetattr(t->fd_in, TCSANOW, &r) != 0) + return false; + + t->open = true; + g_tui = t; + g_winch = 0; + (void)signal(SIGTERM, on_term); + (void)signal(SIGINT, on_term); + (void)signal(SIGHUP, on_term); + (void)signal(SIGQUIT, on_term); +#ifdef SIGWINCH + (void)signal(SIGWINCH, on_winch); +#endif + outs(t, ALT_ON CUR_OFF CLEAR); + out_flush(t); + if (!tui_resize(t)) { + restore(t); + t->open = false; + g_tui = NULL; + return false; + } + return true; +} + +void tui_close(struct tui *t) { + if (!t->open) + return; + restore(t); + t->open = false; + g_tui = NULL; + free(t->cur); + free(t->old); + t->cur = NULL; + t->old = NULL; +} + +void tui_size(struct tui *t, int *w, int *h) { + *w = t->w; + *h = t->h; +} + +void tui_clear(struct tui *t) { + int n = t->w * t->h; + + for (int i = 0; i < n; i++) { + t->cur[i].ch = ' '; + t->cur[i].fg = 7; + t->cur[i].bg = 0; + t->cur[i].attr = 0; + } +} + +void tui_fill(struct tui *t, int x, int y, int w, int h, char ch, + tui_style st) { + if (x < 0) { + w += x; + x = 0; + } + if (y < 0) { + h += y; + y = 0; + } + if (x + w > t->w) + w = t->w - x; + if (y + h > t->h) + h = t->h - y; + if (w <= 0 || h <= 0) + return; + for (int j = y; j < y + h; j++) { + struct tui_cell *row = t->cur + (size_t)j * (size_t)t->w; + for (int i = x; i < x + w; i++) { + row[i].ch = (unsigned char)ch; + row[i].fg = st.fg; + row[i].bg = st.bg; + row[i].attr = st.attr; + } + } +} + +void tui_put(struct tui *t, int x, int y, const char *s, int maxw, + tui_style st) { + if (y < 0 || y >= t->h) + return; + struct tui_cell *row = t->cur + (size_t)y * (size_t)t->w; + for (int i = 0; s[i] != '\0' && x < t->w; i++, x++) { + unsigned char c = (unsigned char)s[i]; + if (maxw > 0 && i >= maxw) + break; + if (x < 0) + continue; + if (c < 0x20) + c = '?'; + row[x].ch = c; + row[x].fg = st.fg; + row[x].bg = st.bg; + row[x].attr = st.attr; + } +} + +void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st, + const char *fmt, ...) { + char b[512]; + va_list ap; + + va_start(ap, fmt); + (void)vsnprintf(b, sizeof b, fmt, ap); + va_end(ap); + tui_put(t, x, y, b, maxw, st); +} + +void tui_box(struct tui *t, int x, int y, int w, int h, tui_style st) { + if (w < 2 || h < 2) + return; + for (int i = 1; i < w - 1; i++) { + tui_put(t, x + i, y, "-", 1, st); + tui_put(t, x + i, y + h - 1, "-", 1, st); + } + for (int j = 1; j < h - 1; j++) { + tui_put(t, x, y + j, "|", 1, st); + tui_put(t, x + w - 1, y + j, "|", 1, st); + } + tui_put(t, x, y, "+", 1, st); + tui_put(t, x + w - 1, y, "+", 1, st); + tui_put(t, x, y + h - 1, "+", 1, st); + tui_put(t, x + w - 1, y + h - 1, "+", 1, st); +} + +void tui_flush(struct tui *t) { + int lfg = -1, lbg = -1, la = -1; + + if (!t->open) + return; + if (t->full) { + outs(t, CLEAR); + memset(t->old, 0, (size_t)t->w * (size_t)t->h * sizeof *t->old); + t->full = false; + } + for (int y = 0; y < t->h; y++) { + struct tui_cell *row = t->cur + (size_t)y * (size_t)t->w; + struct tui_cell *orow = t->old + (size_t)y * (size_t)t->w; + int x = 0; + + while (x < t->w) { + while (x < t->w && row[x].ch == orow[x].ch && + row[x].fg == orow[x].fg && row[x].bg == orow[x].bg && + row[x].attr == orow[x].attr) + x++; + if (x >= t->w) + break; + int start = x; + while (x < t->w && + !(row[x].ch == orow[x].ch && row[x].fg == orow[x].fg && + row[x].bg == orow[x].bg && row[x].attr == orow[x].attr)) + x++; + outf(t, "%s[%d;%dH", ESCS, y + 1, start + 1); + for (int i = start; i < x; i++) { + if (row[i].fg != lfg || row[i].bg != lbg || row[i].attr != la) { + sgr(t, row[i].fg, row[i].bg, row[i].attr); + lfg = row[i].fg; + lbg = row[i].bg; + la = row[i].attr; + } + char c = (char)(row[i].ch != 0 ? row[i].ch : ' '); + out(t, &c, 1); + } + } + } + memcpy(t->old, t->cur, (size_t)t->w * (size_t)t->h * sizeof *t->cur); + out_flush(t); +} + +int tui_tabs_draw(struct tui *t, int x, int y, const char *const *labels, int n, + int active) { + for (int i = 0; i < n; i++) { + int len = (int)strlen(labels[i]) + 2; + + tui_printf(t, x, y, len, i == active ? TUI_TAB_ON : TUI_TAB_OFF, " %s ", + labels[i]); + x += len; + if (i + 1 < n) { + tui_put(t, x, y, " ", 1, TUI_PLAIN); + x += 1; + } + } + return x; +} + +void tui_rule(struct tui *t, int y, char ch, tui_style st) { + tui_fill(t, 0, y, t->w, 1, ch, st); +} + +static void shift_in(struct tui *t, int n) { + if (n >= t->inlen) { + t->inlen = 0; + return; + } + memmove(t->in, t->in + n, (size_t)(t->inlen - n)); + t->inlen -= n; +} + +static int decode(struct tui *t) { + unsigned char *b = t->in; + + if (t->inlen == 0) + return TUI_KEY_NONE; + if (b[0] != ESC_CHAR) { + int k = b[0]; + shift_in(t, 1); + return k == '\t' ? TUI_KEY_TAB : k; + } + if (t->inlen < 2) + return TUI_KEY_NONE; + if (b[1] != '[') { + shift_in(t, 1); + return TUI_KEY_ESC; + } + if (t->inlen < 3) + return TUI_KEY_NONE; + + int k = TUI_KEY_NONE; + switch (b[2]) { + case 'A': + k = TUI_KEY_UP; + break; + case 'B': + k = TUI_KEY_DOWN; + break; + case 'C': + k = TUI_KEY_RIGHT; + break; + case 'D': + k = TUI_KEY_LEFT; + break; + case 'H': + k = TUI_KEY_HOME; + break; + case 'F': + k = TUI_KEY_END; + break; + case 'Z': + k = TUI_KEY_BACKTAB; + break; + default: + break; + } + if (k != TUI_KEY_NONE) { + shift_in(t, 3); + return k; + } + if (b[2] >= '1' && b[2] <= '9') { + int v = 0, i = 2; + while (i < t->inlen && b[i] >= '0' && b[i] <= '9') { + v = v * 10 + (b[i] - '0'); + i++; + } + if (i >= t->inlen) + return TUI_KEY_NONE; /* wait for the final byte */ + if (i < t->inlen && b[i] == '~') { + switch (v) { + case 1: + case 7: + k = TUI_KEY_HOME; + break; + case 2: + k = TUI_KEY_NONE; + break; + case 3: + k = TUI_KEY_DEL; + break; + case 4: + case 8: + k = TUI_KEY_END; + break; + case 5: + k = TUI_KEY_PGUP; + break; + case 6: + k = TUI_KEY_PGDN; + break; + default: + break; + } + shift_in(t, i + 1); + return k; + } + } + /* Unknown CSI: drop the introducer and try again, so a paste of + * unsupported sequences does not turn into random commands. */ + shift_in(t, 3); + return TUI_KEY_NONE; +} + +int tui_key(struct tui *t, int timeout_ms) { + if (g_winch) { + g_winch = 0; + return TUI_KEY_RESIZE; + } + for (;;) { + if (t->inlen > 0) { + int k = decode(t); + if (k != TUI_KEY_NONE) + return k; + } + if (g_winch) { + g_winch = 0; + return TUI_KEY_RESIZE; + } + int wait = (t->inlen > 0) ? 30 : timeout_ms; + fd_set f; + struct timeval tv, *ptv = NULL; + + FD_ZERO(&f); + FD_SET(t->fd_in, &f); + if (wait >= 0) { + tv.tv_sec = wait / 1000; + tv.tv_usec = (wait % 1000) * 1000; + ptv = &tv; + } + int r = select(t->fd_in + 1, &f, NULL, NULL, ptv); + if (r < 0) { + if (errno == EINTR) + continue; + return TUI_KEY_NONE; + } + if (r == 0) { + if (t->inlen > 0) { + if (t->inlen == 1 && t->in[0] == ESC_CHAR) { + t->inlen = 0; + return TUI_KEY_ESC; + } + t->inlen = 0; + } + return TUI_KEY_NONE; + } + ssize_t n = + read(t->fd_in, t->in + t->inlen, sizeof t->in - (size_t)t->inlen); + if (n <= 0) { + if (n < 0 && errno == EINTR) + continue; + return TUI_KEY_ESC; + } + t->inlen += (int)n; + } +} + +/* ---- messages and the application loop ------------------------------- */ + +void tui_run(struct tui *t, struct tui_app *app) { + app->quit = false; + app->view(app->model, t); + tui_flush(t); + for (;;) { + int k = tui_key(t, app->tick_ms > 0 ? app->tick_ms : -1); + struct tui_msg m; + + m.key = 0; + m.w = t->w; + m.h = t->h; + if (k == TUI_KEY_NONE) { + if (app->tick_ms <= 0) + continue; + m.type = TUI_MSG_TICK; + } else if (k == TUI_KEY_RESIZE) { + (void)tui_resize(t); + m.type = TUI_MSG_RESIZE; + } else { + m.type = TUI_MSG_KEY; + m.key = k; + } + if (app->update(app->model, &m)) { + app->view(app->model, t); + tui_flush(t); + } + if (app->quit) + break; + } +} + +/* ---- viewport -------------------------------------------------------- */ + +void tui_viewport_clamp(struct tui_viewport *v, int rows, int height) { + if (rows < 0) + rows = 0; + if (height < 1) + height = 1; + if (v->sel < 0) + v->sel = 0; + if (v->sel >= rows) + v->sel = rows > 0 ? rows - 1 : 0; + if (v->sel < v->top) + v->top = v->sel; + if (v->sel >= v->top + height) + v->top = v->sel - height + 1; + if (v->top > rows - height) + v->top = rows - height; + if (v->top < 0) + v->top = 0; +} + +void tui_viewport_move(struct tui_viewport *v, int delta, int rows, + int height) { + v->sel += delta; + tui_viewport_clamp(v, rows, height); +} + +bool tui_viewport_key(struct tui_viewport *v, int key, int rows, int height) { + switch (key) { + case 'j': + case TUI_KEY_DOWN: + tui_viewport_move(v, 1, rows, height); + return true; + case 'k': + case TUI_KEY_UP: + tui_viewport_move(v, -1, rows, height); + return true; + case TUI_KEY_PGDN: + tui_viewport_move(v, height, rows, height); + return true; + case TUI_KEY_PGUP: + tui_viewport_move(v, -height, rows, height); + return true; + case 'g': + case TUI_KEY_HOME: + v->sel = 0; + tui_viewport_clamp(v, rows, height); + return true; + case 'G': + case TUI_KEY_END: + v->sel = rows - 1; + tui_viewport_clamp(v, rows, height); + return true; + default: + return false; + } +} + +/* ---- table ----------------------------------------------------------- */ + +void tui_table_draw(struct tui *t, tui_rect r, const struct tui_table *tb, + int rows, tui_cell_fn cell, tui_rowstyle_fn rowstyle, + void *ctx) { + int x = r.x; + int height = r.h - 1; + char buf[TUI_CELL_MAX]; + + if (r.w <= 0 || r.h <= 0) + return; + tui_fill(t, r.x, r.y, r.w, 1, ' ', TUI_LABEL); + for (int c = 0; c < tb->ncols && x < r.x + r.w; c++) { + int w = tb->cols[c].width; + + if (w > r.x + r.w - x) + w = r.x + r.w - x; + if (tb->cols[c].right) + tui_printf(t, x, r.y, w, TUI_LABEL, "%*s", w, tb->cols[c].title); + else + tui_printf(t, x, r.y, w, TUI_LABEL, "%-*s", w, tb->cols[c].title); + x += tb->cols[c].width; + if (c + 1 < tb->ncols) + x += 1; + } + if (height < 1) + return; + + struct tui_viewport vp = tb->vp; + tui_viewport_clamp(&vp, rows, height); + for (int i = 0; i < height && vp.top + i < rows; i++) { + int row = vp.top + i; + int y = r.y + 1 + i; + tui_style st = rowstyle != NULL ? rowstyle(ctx, row) : TUI_PLAIN; + bool cur = row == vp.sel; + + x = r.x; + if (cur) { + tui_style fs = st; + fs.attr = (unsigned char)(fs.attr | TUI_REVERSE); + tui_fill(t, r.x, y, r.w, 1, ' ', fs); + st.attr = fs.attr; + } else { + tui_fill(t, r.x, y, r.w, 1, ' ', TUI_PLAIN); + } + for (int c = 0; c < tb->ncols && x < r.x + r.w; c++) { + int w = tb->cols[c].width; + + if (w > r.x + r.w - x) + w = r.x + r.w - x; + buf[0] = '\0'; + if (cell != NULL) + cell(ctx, row, c, buf, sizeof buf); + if (tb->cols[c].right) + tui_printf(t, x, y, w, st, "%*s", w, buf); + else + tui_printf(t, x, y, w, st, "%-*s", w, buf); + x += tb->cols[c].width; + if (c + 1 < tb->ncols) + x += 1; + } + } +} + +bool tui_table_key(struct tui_table *tb, int key, int rows, int height) { + if (tb->ncols == 0 && key == 0) + return false; + return tui_viewport_key(&tb->vp, key, rows, height); +} + +/* ---- tabs ------------------------------------------------------------ */ + +bool tui_tabs_key(int key, int *active, int n) { + switch (key) { + case TUI_KEY_RIGHT: + case TUI_KEY_TAB: + *active = (*active + 1) % n; + return true; + case TUI_KEY_LEFT: + case TUI_KEY_BACKTAB: + *active = (*active + n - 1) % n; + return true; + default: + return false; + } +} + +/* ---- text input ------------------------------------------------------ */ + +void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in, + tui_style st) { + if (r.w < 3 || r.h < 1) + return; + tui_fill(t, r.x, r.y, r.w, 1, ' ', st); + int w = r.w - 2; + int start = 0; + + if (in->pos >= w) + start = in->pos - w + 1; + tui_printf(t, r.x + 1, r.y, w, st, "%.*s", w, in->buf + start); + if (in->focus) { + tui_style cur = TUI_STYLE((unsigned char)(st.fg ^ 0), 7, 0); + int cx = r.x + 1 + in->pos - start; + + if (cx < r.x + 1 + w) { + char c = in->pos < in->len ? in->buf[in->pos] : ' '; + tui_put(t, cx, r.y, &c, 1, cur); + } + } +} + +bool tui_input_key(struct tui_input *in, int key) { + if (!in->focus) + return false; + if (key >= 32 && key < 127) { + if (in->len + 1 >= (int)sizeof in->buf) + return true; + memmove(in->buf + in->pos + 1, in->buf + in->pos, + (size_t)(in->len - in->pos)); + in->buf[in->pos] = (char)key; + in->len++; + in->pos++; + in->buf[in->len] = '\0'; + return true; + } + if (key == 8 || key == 127) { + if (in->pos > 0) { + memmove(in->buf + in->pos - 1, in->buf + in->pos, + (size_t)(in->len - in->pos)); + in->pos--; + in->len--; + in->buf[in->len] = '\0'; + } + return true; + } + if (key == TUI_KEY_DEL) { + if (in->pos < in->len) { + memmove(in->buf + in->pos, in->buf + in->pos + 1, + (size_t)(in->len - in->pos - 1)); + in->len--; + in->buf[in->len] = '\0'; + } + return true; + } + if (key == TUI_KEY_LEFT && in->pos > 0) { + in->pos--; + return true; + } + if (key == TUI_KEY_RIGHT && in->pos < in->len) { + in->pos++; + return true; + } + if (key == TUI_KEY_HOME) { + in->pos = 0; + return true; + } + if (key == TUI_KEY_END) { + in->pos = in->len; + return true; + } + return false; +} + +/* ---- progress and status -------------------------------------------- */ + +void tui_progress(struct tui *t, int x, int y, int width, int pct) { + if (width < 1) + return; + int fill = pct < 0 ? 0 : pct * width / 100; + + if (fill > width) + fill = width; + tui_style st = pct < 0 ? TUI_STYLE(7, 0, TUI_DIM) + : pct < 70 ? TUI_GOOD + : pct < 85 ? TUI_WARN + : TUI_BAD; + for (int i = 0; i < width; i++) + tui_put(t, x + i, y, i < fill ? "#" : "-", 1, + i < fill ? st : TUI_STYLE(7, 0, TUI_DIM)); +} + +void tui_statusbar(struct tui *t, const char *left, const char *right) { + int y = t->h - 1; + + tui_fill(t, 0, y, t->w, 1, ' ', TUI_TITLE); + if (left != NULL) + tui_printf(t, 1, y, t->w - 2, TUI_TITLE, "%s", left); + if (right != NULL) { + int n = (int)strlen(right); + tui_printf(t, t->w - 1 - n, y, n, TUI_TITLE, "%s", right); + } +} diff --git a/tui/tui.h b/tui/tui.h new file mode 100644 index 0000000..6d3c491 --- /dev/null +++ b/tui/tui.h @@ -0,0 +1,198 @@ +/** + * @file tui.h + * @brief A small terminal application toolkit: cell buffer, diff renderer, + * message loop, and a few widgets (viewport, table, tabs, input). + * + * Deliberately no ncurses and no terminfo. Output is plain ANSI (xterm and + * anything that copies it), input is decoded by hand. The shape follows the + * Elm architecture as popularised by Bubble Tea: an application owns a model, + * receives messages (keys, resize, ticks), and draws from the model. Only + * bytes are stored, so a cell is one character wide: ASCII art, not UTF-8 box + * drawing. On z/OS the C compiler's EBCDIC literals are converted by the + * tty, which is why TUI_ESC below is 0x27 there and 0x1b everywhere else. + */ +#ifndef ZTOP_TUI_H +#define ZTOP_TUI_H + +#include <stdbool.h> +#include <stddef.h> +#include <termios.h> + +struct tui_cell { + unsigned char ch; + unsigned char fg; + unsigned char bg; + unsigned char attr; +}; + +typedef struct { + unsigned char fg; /**< 0-7, 7 is white */ + unsigned char bg; /**< 0-7, 0 is black */ + unsigned char attr; /**< TUI_BOLD / TUI_REVERSE / TUI_DIM / TUI_UNDERLINE */ +} tui_style; + +typedef struct { + int x, y, w, h; +} tui_rect; + +#define TUI_BOLD 1u +#define TUI_REVERSE 2u +#define TUI_DIM 4u +#define TUI_UNDERLINE 8u + +#define TUI_STYLE(f, b, a) \ + ((tui_style){(unsigned char)(f), (unsigned char)(b), (unsigned char)(a)}) +#define TUI_PLAIN TUI_STYLE(7, 0, 0) +#define TUI_TITLE TUI_STYLE(7, 4, TUI_BOLD) +#define TUI_LABEL TUI_STYLE(6, 0, 0) +#define TUI_GOOD TUI_STYLE(2, 0, 0) +#define TUI_WARN TUI_STYLE(3, 0, 0) +#define TUI_BAD TUI_STYLE(1, 0, TUI_BOLD) +#define TUI_TAB_ON TUI_STYLE(0, 7, TUI_BOLD) +#define TUI_TAB_OFF TUI_STYLE(7, 0, TUI_DIM) + +enum { + TUI_KEY_NONE = -1, + TUI_KEY_ESC = 256, + TUI_KEY_UP, + TUI_KEY_DOWN, + TUI_KEY_LEFT, + TUI_KEY_RIGHT, + TUI_KEY_HOME, + TUI_KEY_END, + TUI_KEY_PGUP, + TUI_KEY_PGDN, + TUI_KEY_DEL, + TUI_KEY_RESIZE, + TUI_KEY_TAB, + TUI_KEY_BACKTAB +}; + +#define TUI_MAX_W 500 +#define TUI_MAX_H 200 + +struct tui { + int w, h; + int fd_in, fd_out; + struct tui_cell *cur; + struct tui_cell *old; + bool full; + bool open; + struct termios orig; + unsigned char in[64]; + int inlen; + char out[32768]; + int olen; +}; + +bool tui_alloc(struct tui *t, int w, int h); +bool tui_open(struct tui *t); +void tui_close(struct tui *t); + +/** @brief Re-query the size; returns true when it changed and the buffers + * moved. */ +bool tui_resize(struct tui *t); +void tui_size(struct tui *t, int *w, int *h); + +void tui_clear(struct tui *t); +void tui_fill(struct tui *t, int x, int y, int w, int h, char ch, tui_style st); +void tui_put(struct tui *t, int x, int y, const char *s, int maxw, + tui_style st); +void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st, + const char *fmt, ...); +void tui_box(struct tui *t, int x, int y, int w, int h, tui_style st); +void tui_rule(struct tui *t, int y, char ch, tui_style st); +void tui_flush(struct tui *t); + +/** @brief Wait up to @p timeout_ms (-1 = forever) for a key. */ +int tui_key(struct tui *t, int timeout_ms); + +/* ---- messages and the application loop ------------------------------- */ + +enum tui_msg_type { TUI_MSG_KEY, TUI_MSG_RESIZE, TUI_MSG_TICK }; + +struct tui_msg { + enum tui_msg_type type; + int key; /**< TUI_MSG_KEY: a byte or one of TUI_KEY_* */ + int w, h; /**< TUI_MSG_RESIZE: the new size */ +}; + +struct tui_app { + void *model; + /** Handle a message. Returns true when the screen must be redrawn. + * Set @c quit to leave the loop. */ + bool (*update)(void *model, const struct tui_msg *m); + /** Draw the model into the buffer. */ + void (*view)(void *model, struct tui *t); + int tick_ms; /**< 0 = no tick messages */ + bool quit; +}; + +/** @brief Run until the app sets @c quit (or the terminal goes away). */ +void tui_run(struct tui *t, struct tui_app *app); + +/* ---- widgets --------------------------------------------------------- */ + +/** One scroll window: selected row, first visible row. */ +struct tui_viewport { + int sel; + int top; +}; + +void tui_viewport_clamp(struct tui_viewport *v, int rows, int height); +void tui_viewport_move(struct tui_viewport *v, int delta, int rows, int height); +bool tui_viewport_key(struct tui_viewport *v, int key, int rows, int height); + +/** A column of a table. Width counts cells; right aligns numbers. */ +struct tui_col { + const char *title; + int width; + bool right; +}; + +struct tui_table { + const struct tui_col *cols; + int ncols; + struct tui_viewport vp; +}; + +/** Render one cell into @p buf; the buffer is TUI_CELL_MAX bytes. */ +#define TUI_CELL_MAX 128 +typedef void (*tui_cell_fn)(void *ctx, int row, int col, char *buf, size_t len); +typedef tui_style (*tui_rowstyle_fn)(void *ctx, int row); + +/** Draw the header and the visible rows inside @p r. @p rows may be 0. */ +void tui_table_draw(struct tui *t, tui_rect r, const struct tui_table *tb, + int rows, tui_cell_fn cell, tui_rowstyle_fn rowstyle, + void *ctx); + +/** Apply a key to the viewport; true when it was consumed. */ +bool tui_table_key(struct tui_table *tb, int key, int rows, int height); + +/** A row of tabs; returns the x just past the last one. */ +int tui_tabs_draw(struct tui *t, int x, int y, const char *const *labels, int n, + int active); + +/** Cycle tabs with left/right/tab/backtab; true when it was consumed. */ +bool tui_tabs_key(int key, int *active, int n); + +/** A single-line text input. */ +struct tui_input { + char buf[256]; + int len; + int pos; + bool focus; +}; + +void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in, + tui_style st); +/** Insert, erase, move, home/end; true when the key was consumed. */ +bool tui_input_key(struct tui_input *in, int key); + +/** A percentage bar, 0-100 or -1 for "no total". */ +void tui_progress(struct tui *t, int x, int y, int width, int pct); + +/** Fill the bottom row with a help line, left and right halves. */ +void tui_statusbar(struct tui *t, const char *left, const char *right); + +#endif |
