summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorSean Kurtz <seankurtz75@gmail.com>2026-11-27 18:10:43 -0600
committerSean Kurtz <seankurtz75@gmail.com>2026-11-27 18:10:43 -0600
commitbed906ea03f44454baa7089bb3cb975f94d77bcc (patch)
tree1b2f1fb4a7be820454792832df76c17f1da8069a
parent327bb5eef966394d487046d3bfe2420a66d50a99 (diff)
downloadztop-bed906ea03f44454baa7089bb3cb975f94d77bcc.tar.gz
views: PS, FS and LOG, and a DEC-graphics frame
Two changes that share files -- the views, and the screen they are drawn on -- so one commit; splitting them would mean splitting src/ztop.c and tui/tui.h by hunk, which is not a split a reviewer could follow. The views. Seven tabs instead of four: PS (w_getpsent), FS (w_getmntent plus statvfs) and LOG, a read-only extended MCS console behind -c. LOG needs supervisor state, so MCSOPER and MCSOPMSG live in src/zmcs.s: it switches to supervisor state, calls the macro, switches back, and hands the caller a copy of the message data block. src/mdb.c walks that MDB (IEAVM105) for the job name and the text line, and is separate from src/ztop.c because it is the one place ztop parses bytes written by another address space, so it is worth a test that runs anywhere. The small structs become C23 typedefs, src/vsm.c keeps the 16M line apart, and README lists the seven views and the keys they moved. The screen. The frame, the meters and the scrollbar were the last parts that said "curses". Borders and meters are now the DEC Special Graphics set, designated into G0 with ESC ( 0 and released with ESC ( B, with a fallback to + - | # when TERM is not one we know; the meters are shade fill over a horizontal rule instead of a [#### ] bar; table selection is a background colour instead of reverse video, which is the tell almost everyone recognises as curses; the tab row separates with a gap instead of |; titles are a dim style and the frame is grey so the accent colour means selection. The designation is tracked per cell, because an SGR reset does not leave the graphics set, and only the cells that carry a border glyph pay for it -- six bytes a row at 80 columns. Everything stays 7-bit ASCII in the source, which is what .gitattributes now enforces for the whole tree: one rule, ISO8859-1 in the working tree, the same line the zopen git port uses, so a checkout on z/OS is tagged ASCII for make, sh, awk and the compiler and no file needs a hand tag. Verified on Linux: make test TESTCC=cc green (test_vsm, test_sys, test_mdb, tui/test_tui, leakcheck), make tidy adds no finding to the ten that predate this, src/ztop.c passes -fsyntax-only with the project's warnings. The frame was checked against a painted screen with tests/screen.py, which now understands ESC ( 0. Not yet built on z/OS: the CBT build, make check and make leakcheck run after the push and the PR carries their result.
-rw-r--r--.clang-tidy6
-rw-r--r--.gitattributes7
-rw-r--r--.gitignore5
-rw-r--r--DESIGN.md231
-rw-r--r--Makefile46
-rw-r--r--README.md21
-rw-r--r--src/mdb.c50
-rw-r--r--src/mdb.h37
-rw-r--r--src/sys.c8
-rw-r--r--src/sys.h29
-rw-r--r--src/uss.c172
-rw-r--r--src/uss.h61
-rw-r--r--src/vsm.c53
-rw-r--r--src/vsm.h36
-rw-r--r--src/zmcs.c22
-rw-r--r--src/zmcs.h73
-rw-r--r--src/zmcs.s185
-rw-r--r--src/ztop.c1433
-rw-r--r--tests/__pycache__/screen.cpython-315-pytest-9.1.1.pycbin4406 -> 0 bytes
-rw-r--r--tests/screen.py37
-rw-r--r--tests/test_mdb.c90
-rw-r--r--tests/test_sys.c2
-rw-r--r--tests/test_vsm.c33
-rw-r--r--tui/Makefile2
-rw-r--r--tui/demo.c2
-rw-r--r--tui/test_tui.c149
-rw-r--r--tui/tui.c448
-rw-r--r--tui/tui.h265
28 files changed, 2896 insertions, 607 deletions
diff --git a/.clang-tidy b/.clang-tidy
index 1962859..33455bc 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -1,6 +1,6 @@
---
-# 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
+# Checks for ztop. Run with `make tidy`. Every check named here either
+# finds real bugs here (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: >
@@ -82,7 +82,7 @@ Checks: >
# scanner)
WarningsAsErrors: ''
-HeaderFilterRegex: '^.*/src/.*\.h$'
+HeaderFilterRegex: "^(.*/)?(src|tui)/.*\\.h$"
FormatStyle: file
SystemHeaders: false
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..3d92e1b
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,7 @@
+# One rule, no exceptions: the repository is UTF-8 and the working tree is
+# ISO8859-1, so a checkout on z/OS is tagged ASCII, which is what make, sh,
+# awk and the compiler need when they read it through the EBCDIC converter.
+# This is the same line the zopen community's git port uses. Everything in
+# the tree stays 7-bit; a box character belongs on the terminal, not in the
+# source.
+* text eol=lf working-tree-encoding=ISO8859-1
diff --git a/.gitignore b/.gitignore
index f2ed478..dacd141 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,8 @@ CEEDUMP.*
*.lst
compile_commands.json
tests/test_sys
+
+# agent notes for this checkout: host-specific, not part of the tree
+AGENTS.md
+__pycache__/
+tests/test_mdb
diff --git a/DESIGN.md b/DESIGN.md
index 7c4f349..b6712ca 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -119,7 +119,6 @@ footprint plus holes is the mapped extent; SQA, LSQA and the private area
have no such request and show used, free and mapped without a total.
## System and jobs
-
The CVT gives the system name (`CVTSNAME`, CVT+0x154) and the ASVT
(`CVTASVT`, CVT+0x22C). The ASVT holds `ASVTMAXU` at +0x204 and the
entries at +0x210; bit 0 of an entry means the ASID is free, otherwise it
@@ -150,6 +149,103 @@ and their totals are not knowable this way. The paging view reads ASMVT
(`CVTASMVT`, CVT+0x2C0) for the common and PLPA page data sets' flags and
the VIO journal count; it does not read the data-set names yet.
+## The UNIX views
+
+Two views read z/OS UNIX, both in the problem state, both without
+allocation. `src/uss.c` holds the two readers; `src/uss.h` the two fixed
+tables.
+
+PS walks `w_getpsent` (BPX1GPS) from process token 0, which the callable
+services manual defines as "the first process in the system", and calls
+it again with each returned token until it answers 0 (no more processes
+this caller may see) or -1 (error, errno in the return code). The
+columns are documented members of `W_PSPROC` in `<sys/ps.h>`: `ps_pid`,
+`ps_ppid`, `ps_euid`, `ps_state` (letter in `PS_STATECHAR`, an `S`
+suffix for `PS_SWAP`), and `ps_usertime` + `ps_systime` in
+`CLOCKS_PER_SEC` units. The service has no job name, no ASID and no
+thread count, so PS and JOBS are not cross-linked and no column pretends
+otherwise.
+
+FS calls `w_getmntent` once with the mnt3 mapping -- `MNTE3H_ID` in
+`mnt3H_cbid`, `sizeof(MNTE3)` in `mnt3H_cblen`, `sizeof(W_MNTENT3)` in
+`mnt3H_bodylen` -- and takes the mount point, the FILESYS type name and
+the aggregate data set name from the entries. Size, free space and the
+read-only flag then come from `statvfs()` per mount, not from
+`mnt3_mode`: `ST_RDONLY` is the documented POSIX bit, while the mount
+mode word would have to be decoded into meaning the C header does not
+name.
+
+The caps are `USS_MAX_FS 64` and `USS_MAX_PS 128`; on CBT the counts are
+31 file systems and 60 processes. The `w_getmntent` buffer is one
+file-scope static of 64 `W_MNTENT3` and nothing at all is allocated; a
+count past a cap sets `truncated`, which the footer prints instead of
+hiding. Each reader runs only when its view is on screen, so the tick
+that refreshes STORAGE does not pay for them.
+
+Unverified, and said so on purpose: the PID numbers are the raw `ps_pid`
+values and were not cross-checked against `ps -ef`; the mount status byte
+and the quiesce owner are not shown; there is no CPU percentage (only
+total CPU time) and no per-process memory.
+
+## The console
+
+`MCSOPER` and `MCSOPMSG` are the only services ztop needs that no C
+program can call: SA22-7614 puts both at "supervisor state and any PSW
+key". They live in `src/zmcs.s`, which mirrors `src/zvslist.S`: it
+saves the caller's registers, points R2 at a request block, switches to
+supervisor state for the call, switches back, and leaves the service
+return code in the block. The block is the C struct in `src/zmcs.h`,
+and the offsets in the stub are its -m32 offsets (40 for the save area,
+184 for the console status area); `src/ztop.c` asserts them under
+`__MVS__`, because the same struct on a 64-bit host has a different
+shape and the check would only be noise there.
+
+The stub is plain assembler, not `.S`, and that is deliberate. The `.S`
+path sends the source through clang's preprocessor, and that stage
+squeezes the runs of blanks which hold a continuation character in
+column 72: a `MCSOPER` call with ten operands cannot survive it. Two
+minimal files settled it -- identical bytes, `.s` assembled and `.S`
+failed with `ASMA141E Bad character in operation code` -- so the rule in
+the Makefile is a second rule for this one file, with no preprocessor.
+
+Opening the console is opt-in (`ztop -c`), because the failure mode is
+not a return code. On CBT, without APF, the first `MODESET MODE=SUP`
+ended the task: `CEE3250C The system or user abend S047 R=NULL was
+issued. From entry point log_start`. A program that cannot enter
+supervisor state does not get told so politely, so ztop does not try
+unless asked; without `-c` the LOG view says `console off: ztop -c after
+make auth`. `make auth` runs `extattr +ap ./ztop`, which marks the
+file; the library it sits in still has to be in the APF list, which is
+an operator or system programmer action, and the user needs READ on
+`MVS.MCSOPER.ZTOP`.
+
+The console is a log, not a command line: no `OPERPARM` area is passed,
+so it takes the session defaults (authority INFO, message level ALL,
+scope *ALL), which is what reading wants. Issuing commands is `MGCRE`,
+which also needs OPERCMDS -- a different feature, not a switch.
+
+A message lives in the console's data space, so the stub copies it out
+while still in supervisor state: the copy length is the MDB's own
+`MDBLEN` clipped to the caller's buffer (4096 bytes in the model), and
+the C side then walks the object chain with every length checked against
+the copy -- the bytes come from another address space. The text object
+(type 4) carries the line at +9, the general object (type 1) the job
+name at +48 (IEAVM105).
+
+Nothing allocates. The ring is `LOG_LINES 256` lines of `LOG_COLS 200`
+inside the model, so 51 KB of a static struct; a full ring overwrites
+its oldest line and the footer says `oldest dropped`. `MCSOPMSG` is
+called at most 200 times per tick, which bounds a burst, and in the
+steady state once -- the single call that returns RC 8 ("nothing
+queued"). The console stays open when another view is on screen, so the
+queue does not build up behind it, and it is closed on quit and after
+`tui_run` returns, so a signal that ends the loop still deactivates it.
+
+Unverified, and the reason the tab says so little: with APF in place and
+MVS.MCSOPER.ZTOP granted, not one message has been read yet. The
+activate and get-msg paths have assembled, linked and aborted at
+MODESET; nothing beyond that has run.
+
## The terminal
`tui/` is a small library, not a curses replacement: a cell buffer with a
@@ -159,7 +255,8 @@ message (key, resize, tick) and redraws from the model -- because it keeps
the terminal code out of the application and gives every view the same
keys. The widgets are a viewport with its own selection and scroll
offset, a table built from columns and a cell callback, tabs, a single
-line input, a progress bar and a status line; an application that wants no
+line input, a progress bar, a sparkline, a scrollbar and a status
+line; an application that wants no
tabs simply never draws them. The mouse is part of the message loop: SGR
mouse reporting (1006) turns a click into a `TUI_MSG_MOUSE` with 0-based
cells, and `tui_tabs_hit` answers which tab a column belongs to, so the
@@ -176,24 +273,123 @@ All modes currently end at 12 gets, 0 frees and 17776 bytes in use.
The buffer keeps one screen of cells and one of what is already on the
glass, and writes only the runs that differ, with one style change per
run. The library is compiled into the program rather than linked from an
-archive, but `tui/Makefile` can build `libtui.a` for reuse. No Unicode:
-the box and the bar are `+`, `-`, `|`, `#`, because the terminal path is
-an EBCDIC-to-ASCII conversion that is not a charset translation.
+archive, but `tui/Makefile` can build `libtui.a` for reuse. Glyphs are
+7-bit: the frame and the meters use the DEC Special Graphics set (`l q k
+x m j`, shade `a`) designated into G0 with `ESC ( 0` and released with
+`ESC ( B`. That is an ASCII escape sequence, which the EBCDIC-to-ASCII
+output path does carry; a UTF-8 box character would not survive it, since
+the path is a byte conversion and not a charset translation. A terminal
+whose `TERM` is not one we recognise gets `+ - | #` instead, because
+`lqqqk` where a corner belongs is worse than a plain frame. Selection is
+a background, not reverse video: reverse video is what makes a table read
+as curses.
+
+A view is one titled panel across the body -- `+-- STORAGE ---...---+`
+in the source, drawn as a box on a terminal that has DEC graphics -- with
+the tab row above it, the machine's identity on the top bar and the keys
+on the status line, so that every view has the same frame and the screen
+reads as one program. Numbers that carry a view (the area's
+used/free/mapped/total and its share in use, the address-space count) sit
+either on the panel's first row or in its bottom border, next to the
+table; whatever does not fit at the current width is dropped rather than
+truncated into the field beside it.
-Three z/OS details are load-bearing:
+Four z/OS details are load-bearing:
- The escape character in the source has to be EBCDIC X'27'. The tty
converts EBCDIC to ASCII on output, so a C `"\x1b"` arrives as X'8F';
- X'27' arrives as the ESC the terminal expects. `src/tui.c` picks the
+ X'27' arrives as the ESC the terminal expects. `tui/tui.c` picks the
byte with `#ifdef __MVS__`; input is not converted, so keys arrive as
- EBCDIC and are mapped there too.
+ EBCDIC and are mapped there too. The same conversion passes the DEC
+ `ESC ( 0` designation through unchanged, which is why the glyph choice
+ above costs nothing on z/OS.
- `TIOCGWINSZ` succeeds with zero columns and rows. The size comes from a
cursor-position report (`ESC[6n`, answer `ESC[row;colR`) with a timeout,
then `COLUMNS`/`LINES`, then 80x24. `SIGWINCH` is handled where the
- system sends it.
+ system sends it; every handler is installed with `sigaction`, not
+ `signal`, because the z/OS runtime prefers it.
- `-D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L` is what exposes termios,
`select` and `clock_gettime` in the z/OS headers; `nanosleep` and `usleep`
are not declared, so the refresh wait is `select`.
+- `.gitattributes` tags the whole working tree ISO8859-1 with one rule, the
+ way the zopen projects do it (their `meta` project tags everything UTF-8,
+ their git port tags everything ISO8859-1 through the portable
+ `working-tree-encoding` attribute): no per-file exceptions, because a
+ rule with exceptions is a rule someone will get wrong. Sources read
+ through the EBCDIC converter need that ASCII tag, and holding the tree to
+ 7-bit is also why the frame is ASCII in the source and only the terminal
+ draws the box. `make tag` retags a tree that predates the file.
+
+## One table for the keys
+
+The keys are a table of bindings (`tui_binding`: key, label, group, the
+tabs it applies to, whether it fits in the footer). The footer line and
+the `?` overlay are both generated from that table, so a key cannot be
+documented in one place and forgotten in the other, and the tab mask keeps
+`/`, `j`/`k` and `s` out of views where they would do nothing. The
+application's key handling is one `switch`-free chain of comparisons in
+`update()`; the table is a description of it, not a second implementation.
+
+## Colour and layout
+
+A cell carries a foreground and a background from the xterm-256 palette
+(`TUI_COLOR_DEFAULT` is 255 and is emitted as `;39`/`;49` so a terminal
+keeps its own default background). The palette is chosen for a dark
+terminal over SSH and is not configurable: no dependency, no theme file.
+Geometry is computed once per frame from `tui_rect` primitives
+(`tui_split_v`, `tui_split_h`, `tui_inset`, `tui_rect_hit`), and the same
+rectangles are handed to the mouse hit-test, so a click cannot land on a
+row the table did not draw.
+
+## Storage, the 16M line and folding
+
+`vsm_info` and `vsm_subpool` carry `below` and `above` on top of `used`: a
+block is counted on the side of the 16M line its first byte is on, which
+is why the two do not always add up to `used` for a block that straddles
+it. The private-area table can be folded per owning TCB: the folded rows
+are rebuilt from `vsm_info.sub[]` after every collect (sort by TCB, one
+linear pass to group, no allocation), carry `SUBS`, `USED`, `<16M`, `>16M`
+and `LINE`, and `Enter` opens the subpools that make the row up. The
+filter narrows the same order arrays the table, the detail line, the popup
+and the mouse read, so there is one place a row index is translated.
+
+## C23 and C++ callers
+Every build is `-std=c23`: `nullptr`, `constexpr`, `static_assert`, `bool`
+and integer/enum-typed limits (`enum { TUI_MAX_W = 500 };`). The library
+types are `typedef struct name { ... } name;`, so code says `tui *t`, not
+`struct tui *t`. `tui/tui.h` wraps its declarations in `extern "C"`, so a
+C++ program can include the library header; the portable tree is built
+with the same flags the z/OS build uses.
+
+One `constexpr` does not survive the target compiler: IBM Open XL 2.2
+rejects `static constexpr char ZTOP_VERSION[] = "0.3";` with "constexpr
+initializer evaluates to -16 which is not exactly representable in type
+'const char'", where clang 23 on Linux accepts it. That constant stays a
+plain `static const char[]`; the rest of the tree's `constexpr` use is
+scalar and builds on both.
+
+## Tidy findings that stand
+
+`make tidy` is the standard, and the tree still has four groups of findings
+that predate it. They are recorded here so that a change touching these
+files can say why they remain rather than being silently carried:
+
+- `bugprone-signed-bitwise` on `attr & TUI_BOLD` and the `flags & 0x0F`
+ tests: the operand is `unsigned char` and integer promotion makes the
+ operator signed. The values are small, the intent is a bit test, and the
+ flag mask is masked again before use; an explicit `unsigned` cast at
+ every site would add noise without changing a result.
+- `bugprone-unchecked-string-to-number-conversion` on `atoi(COLUMNS)` and
+ `atoi(LINES)` in the terminal size fallback. A terminal size is
+ advisory: a malformed value falls back to 80x24, which is the behaviour
+ wanted, and `strtol` with an error path would not be better.
+- `clang-analyzer-security.ArrayBound` at the `region[]` guard in
+ `src/vsm.c:259`: one analyzer false positive, the bound is checked
+ immediately before the access. (The second one this note used to
+ mention, at the one-cell `tui_put` call, went away when `tui_sparkline`
+ started passing a one-character string.)
+- `cert-int09-c` for the key enum before this change: now every enumerator
+ has its value written out, which is also what makes the order irrelevant.
## Open
@@ -204,8 +400,10 @@ Three z/OS details are load-bearing:
- Area sizes for SQA, LSQA and the private area. `VSMLIST` reports
allocation and free space, not the limit; a percentage there needs a
different source, and none is planned.
-- `SP=PVT` output is already grouped by owning TCB, but the view still
- prints one list; per-TCB folding is a display change, not a data change.
+- `SP=PVT` folding by owning TCB (`t`), the inspector pane (`i`), the
+ filter (`/`) and the command line (`:`) are exercised on a Linux pty with
+ synthetic data only; the folded table has not been seen against a real
+ `VSMLIST` PVT answer yet.
- The full-screen view has been exercised on a Linux pty and a z/OS pty:
view switching, area switching, scrolling, help, quit and the cursor
restore. What has not been seen is a real xterm over SSH answering the
@@ -214,3 +412,14 @@ Three z/OS details are load-bearing:
- The jobs view lists every address space and its ASID and ASCB; job name
lookup uses the documented `ASCBJBNS` pointer. Sorting, filtering and
per-job storage are not implemented.
+- CPU-measurement counters. The machine has the facility: a probe read
+ `STFLE` bit 67 (counter facility), 68 (sampling) and 142 (store CPU
+ counter multiple) on CBT on 2026-11-26 and found all three set. A
+ problem-state program still may not read a counter: the same probe took
+ the privileged-operation program check at `ECCTR` (`S0C2`, reason 2),
+ which is what SA23-2260-08 p.2-27 specifies while bit 15 of control
+ register 0 is zero - its initialised value, p.2-1, and a bit only the
+ installation sets. A counters view would therefore need an authorised
+ caller or a change to the system, not code in `ztop`. Counter meaning
+ for this z16, if it ever becomes readable, is SA23-2261-09, numbers 128
+ to 287.
diff --git a/Makefile b/Makefile
index 96ab36c..ff2f2bf 100644
--- a/Makefile
+++ b/Makefile
@@ -9,6 +9,7 @@
# 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 tidy clang-tidy over the portable sources
# make demo tui/demo, the library on its own
# make clean remove what the targets above write
#
@@ -39,13 +40,13 @@ 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/sys.h tui/tui.h
+SRC = src/ztop.c src/vsm.c src/sys.c src/uss.c src/mdb.c src/zmcs.c tui/tui.c
+OBJ = src/zvslist.o src/zmcs.o
+HDR = src/vsm.h src/sys.h src/uss.h src/mdb.h tui/tui.h
# The portable half: no z/OS services, no terminal.
TESTCC = cc
-TESTFLAGS = -std=c17 -g -O1 -Wall -Wextra -Wshadow -Wpedantic \
+TESTFLAGS = -std=c23 -g -O1 -Wall -Wextra -Wshadow -Wpedantic \
-D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L
# Language Environment sees every heap request the program makes. Its
@@ -54,12 +55,13 @@ TESTFLAGS = -std=c17 -g -O1 -Wall -Wextra -Wshadow -Wpedantic \
# allocated and never freed. HEAPCHK(ON) additionally walks the heap at
# every call, so a double free or an overlay abends instead of hiding.
-# git checkout leaves every source untagged, and the z/OS tools then read
-# ASCII through the EBCDIC converter: make spins on the Makefile, sh
-# rejects the script, awk reads garbage. Run this once after a checkout.
+# The working tree arrives tagged ISO8859-1 from .gitattributes, so this is
+# only for a tree that predates that file or a file written by hand. The
+# tag matters because make, sh, awk and the compiler read these files
+# through the EBCDIC converter and see ASCII, not EBCDIC.
tag:
@-chtag -t -c ISO8859-1 Makefile README.md DESIGN.md tests/*.sh tests/*.py
- @-chtag -t -c ISO8859-1 src/*.c src/*.h src/*.S tui/*.c tui/*.h
+ @-chtag -t -c ISO8859-1 src/*.c src/*.h src/*.S src/*.s tui/*.c tui/*.h
@-chtag -t -c ISO8859-1 tui/Makefile tui/test_tui.c tui/demo.c
all:
@@ -73,17 +75,28 @@ ztop: $(SRC) $(OBJ) $(HDR)
src/zvslist.o: src/zvslist.S
$(CC) $(CFLAGS) $(ASFLAGS) -c -o $@ src/zvslist.S
+# zmcs.s is plain assembler on purpose: the .S path puts the source
+# through clang's preprocessor, and that squeezes the runs of blanks
+# which hold a continuation character in column 72. A macro call that
+# needs more than one line cannot survive it, and this stub has no
+# #ifdef to justify the preprocessor anyway.
+src/zmcs.o: src/zmcs.s
+ $(CC) $(CFLAGS) -fno-integrated-as -c -o $@ src/zmcs.s
+
check: ztop
./ztop
./ztop -a sqa
./ztop -a pvt
./ztop -j
-test: tests/test_vsm.c tests/test_sys.c src/vsm.c src/sys.c tui/test_tui.c tui/tui.c
+test: tests/test_vsm.c tests/test_sys.c tests/test_mdb.c src/vsm.c src/sys.c \
+ src/mdb.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) -Isrc -o tests/test_sys tests/test_sys.c src/sys.c
./tests/test_sys
+ $(TESTCC) $(TESTFLAGS) -Isrc -o tests/test_mdb tests/test_mdb.c src/mdb.c
+ ./tests/test_mdb
$(TESTCC) $(TESTFLAGS) -Itui -o tui/test_tui tui/test_tui.c tui/tui.c
./tui/test_tui
@sh tests/leakcheck.sh --selftest
@@ -91,8 +104,23 @@ test: tests/test_vsm.c tests/test_sys.c src/vsm.c src/sys.c tui/test_tui.c tui/t
demo: tui/demo.c tui/tui.c
$(TESTCC) $(TESTFLAGS) -Itui -o tui/demo tui/demo.c tui/tui.c
+# ztop.c needs the z/OS headers, so the tidy pass covers everything else:
+# the parser, the system helpers, the library and their tests.
+tidy:
+ clang-tidy src/vsm.c src/sys.c src/uss.c src/mdb.c src/zmcs.c \
+ tui/tui.c tests/test_vsm.c tests/test_sys.c tests/test_mdb.c \
+ tui/test_tui.c tui/demo.c -- \
+ $(TESTFLAGS) -Isrc -Itui
+
leakcheck: ztop
@sh tests/leakcheck.sh ./ztop
+# The console needs APF: extattr marks this file, and the library it sits
+# in still has to be in the APF list. Then the user needs READ on
+# MVS.MCSOPER.ZTOP, and ztop is started with -c.
+auth:
+ extattr +ap ./ztop
+ ls -E ./ztop
+
clean:
rm -f ztop $(OBJ) tests/test_vsm tests/test_sys tui/test_tui tui/demo
diff --git a/README.md b/README.md
index cd5e192..66bf4c9 100644
--- a/README.md
+++ b/README.md
@@ -69,12 +69,13 @@ ztop -j one line per address space
ztop -p auxiliary storage and page data sets
ztop -x dump the raw VSMLIST work and data areas
ztop -d [seconds] interactive, 10 s refresh (1..60)
+ztop -d -c the same, with the MCS console (LOG view)
```
With a terminal and no report option, `ztop` starts the full-screen view.
Anything that selects a report (`-a`, `-s`, `-j`, `-x`) or pipes the output
gets the one-shot text instead, suitable for `grep` and for a shell
-prompt. There are four views, selected with `TAB`:
+prompt. There are seven views, selected with `TAB`:
| view | |
| --- | --- |
@@ -82,25 +83,35 @@ prompt. There are four views, selected with `TAB`:
| SYSTEM | system and host, IPL date and time, real storage, address spaces |
| JOBS | ASID, job name and ASCB address for every address space |
| PAGING | auxiliary storage flags and the page data sets from ASMVT |
+| PS | PID, PPID, UID, state and CPU time per process, from `w_getpsent` |
+| FS | mount point, type, size, free space and read-only, from `w_getmntent` and `statvfs` |
+| LOG | the operator console, read only, from an extended MCS console (`-c`, needs APF) |
| key | |
| --- | --- |
| `TAB`, `Shift-TAB`, click a tab | next / previous view |
-| `1`..`4` | in STORAGE: CSA, SQA, LSQA, private; elsewhere: switch view |
+| `1`..`7` | in STORAGE `1`..`4` are the areas; `5`..`7`, and any digit in another view, switch view |
| `p` | pause/resume refresh |
| `r` | collect now |
| `+`/`-` | refresh 1..60 s |
| `j`/`k`, arrows, `PgUp`/`PgDn`, `g`/`G` | move and scroll the selected table |
| wheel, click a row | scroll, select a row |
| `s`, `S` | next sort column, reverse it (the header shows both) |
-| `Enter` | every field of the selected subpool |
+| `Enter` | every field of the selected subpool, or of the TCB |
+| `i` | inspector pane beside the table (width permitting) |
+| `t` | in the private area: fold the subpools by owning TCB |
+| `/` | filter the table (`Enter` keeps it, `ESC` clears it) |
+| `:` | command: `csa` `sqa` `lsqa` `pvt` `sys` `jobs` `page` `ps` `fs` `fold` `pause` `help` `quit` |
| `?` | help |
| `q` | quit |
Each table remembers its own selection and scroll position, so switching
-views does not lose your place. The status line shows the subpool or
+views does not lose your place; a filter survives a tab switch, and `ESC`
+on the filter line removes it. The status line shows the subpool or
address space under the cursor. The design, including why the data
-sources are what they are, is in [DESIGN.md](DESIGN.md).
+sources are what they are, is in [DESIGN.md](DESIGN.md); how a change is
+built, tested and reviewed, and the terms for using an AI agent at all,
+are in [AGENTS.md](AGENTS.md).
## What it is not
diff --git a/src/mdb.c b/src/mdb.c
new file mode 100644
index 0000000..4deb4a5
--- /dev/null
+++ b/src/mdb.c
@@ -0,0 +1,50 @@
+/** @file mdb.c
+ * @brief The MDB object walk. See src/mdb.h.
+ */
+#include "mdb.h"
+
+#include <string.h>
+
+/** Copy @p n bytes, stop at the first blank or NUL, terminate. */
+static void trim_copy(char *dst, size_t len, const char *src, int n) {
+ int i = 0;
+
+ if (len == 0)
+ return;
+ while (i < n && src[i] != '\0' && src[i] != ' ')
+ i++;
+ if ((size_t)i >= len)
+ i = (int)len - 1;
+ (void)memcpy(dst, src, (size_t)i);
+ dst[i] = '\0';
+}
+
+bool mdb_line(const char *mdb, int len, char *job, size_t joblen, char *text,
+ size_t textlen) {
+ const unsigned char *m = (const unsigned char *)mdb;
+ int p;
+ int found = 0;
+
+ if (joblen > 0)
+ job[0] = '\0';
+ if (textlen > 0)
+ text[0] = '\0';
+ if (mdb == nullptr || len <= 0)
+ return false;
+ /* The header is 12 bytes; the objects follow it. */
+ for (p = 12; p + 4 <= len;) {
+ int olen = (m[p] << 8) | m[p + 1];
+ int otype = (m[p + 2] << 8) | m[p + 3];
+
+ if (olen < 4 || p + olen > len)
+ break; /* a length that does not fit is not a length */
+ if (otype == 1 && olen >= 56) {
+ trim_copy(job, joblen, (const char *)m + p + 48, 8);
+ } else if (otype == 4 && olen > 9 && found == 0) {
+ trim_copy(text, textlen, (const char *)m + p + 9, olen - 9);
+ found = 1;
+ }
+ p += olen;
+ }
+ return found != 0;
+}
diff --git a/src/mdb.h b/src/mdb.h
new file mode 100644
index 0000000..58ba606
--- /dev/null
+++ b/src/mdb.h
@@ -0,0 +1,37 @@
+/** @file mdb.h
+ * @brief Pull a job name and a line of text out of a message data block.
+ *
+ * An MDB (IEAVM105) is a chain of objects, each two bytes of length
+ * followed by two of type. The general object (type 1) names the job
+ * that wrote the message at +48; a text object (type 4) holds its line at
+ * +9. The walk is here rather than in src/ztop.c because this is the one
+ * place ztop parses bytes that came from another address space, and it is
+ * the part worth a test that runs anywhere.
+ */
+#ifndef ZTOP_MDB_H
+#define ZTOP_MDB_H
+
+#include <stddef.h>
+
+/** Largest text line kept: a console line is at most 132 columns. */
+enum { MDB_TEXT_MAX = 200 };
+
+/**
+ * @brief Extract the job name and the first text object of an MDB copy.
+ *
+ * @param mdb the block as zmcs() copied it out of the console's space
+ * @param len how many bytes of it are valid
+ * @param job out: job name, blank padded or empty; never left unterminated
+ * @param joblen size of @p job
+ * @param text out: the line, trimmed; empty when there is none
+ * @param textlen size of @p text
+ * @return true when a text object was found
+ *
+ * Every length read is checked against @p len before it is used: the
+ * block was written by someone else, so a length in it is input, not a
+ * fact.
+ */
+bool mdb_line(const char *mdb, int len, char *job, size_t joblen, char *text,
+ size_t textlen);
+
+#endif /* ZTOP_MDB_H */
diff --git a/src/sys.c b/src/sys.c
index 6618841..3fd0819 100644
--- a/src/sys.c
+++ b/src/sys.c
@@ -60,7 +60,7 @@ static unsigned int nib(uint32_t v, unsigned int shift) {
return (v >> shift) & 0xFu;
}
-bool zipl_decode(uint32_t date, uint32_t hundredths, struct zipl *out) {
+bool zipl_decode(uint32_t date, uint32_t hundredths, zipl *out) {
static const unsigned int mdays[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
};
@@ -96,7 +96,7 @@ bool zipl_decode(uint32_t date, uint32_t hundredths, struct zipl *out) {
return true;
}
-bool zsys_read(struct zsys *z) {
+bool zsys_read(zsys *z) {
#ifdef __MVS__
uintptr_t cvt, asvt;
uint32_t maxu, entry;
@@ -112,7 +112,7 @@ bool zsys_read(struct zsys *z) {
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];
+ zjob *j = &z->job[z->njobs];
uint32_t namep;
entry = rd32(asvt + 0x210 + (uintptr_t)i * 4);
@@ -140,7 +140,7 @@ bool zsys_read(struct zsys *z) {
#endif
}
-bool zpage_read(struct zpage *p) {
+bool zpage_read(zpage *p) {
#ifdef __MVS__
uintptr_t cvt = rd32(0x10);
uintptr_t asmvt;
diff --git a/src/sys.h b/src/sys.h
index c52ee42..31c9950 100644
--- a/src/sys.h
+++ b/src/sys.h
@@ -11,43 +11,42 @@
#ifndef ZTOP_SYS_H
#define ZTOP_SYS_H
-#include <stdbool.h>
#include <stdint.h>
-#define ZJOB_MAX 512
+enum { ZJOB_MAX = 512 };
/** @brief One address space. */
-struct zjob {
+typedef struct zjob {
unsigned int asid;
uint32_t ascb;
char name[9];
-};
+} zjob;
/** @brief The IPL date and time, decoded from the SMCA. */
-struct zipl {
+typedef struct zipl {
unsigned int year;
unsigned int month;
unsigned int day; /**< day of month */
unsigned int hour;
unsigned int minute;
unsigned int second;
-};
+} zipl;
/** @brief What the system view shows. */
-struct zsys {
+typedef 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];
+ zjob job[ZJOB_MAX];
bool ipl_ok;
- struct zipl ipl;
+ zipl ipl;
uint64_t real_k; /**< real storage online at IPL, in K */
uint32_t cvt;
uint32_t smca;
-};
+} zsys;
/**
* @brief Decode SMCAIDTE (0CYYDDDF, packed) and SMCAITME (hundredths).
@@ -56,17 +55,17 @@ struct zsys {
* @param out Where to write.
* @return false when the fields do not describe a real date and time.
*/
-bool zipl_decode(uint32_t date, uint32_t hundredths, struct zipl *out);
+bool zipl_decode(uint32_t date, uint32_t hundredths, zipl *out);
/**
* @brief Fill @p z from the CVT, the SMCA 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);
+bool zsys_read(zsys *z);
/** @brief Auxiliary storage state, from the ASMVT. */
-struct zpage {
+typedef struct zpage {
bool common_pds; /**< a common page data set exists */
bool common_full;
bool plpa_pds;
@@ -77,13 +76,13 @@ struct zpage {
bool warm_start;
unsigned int vio_ci; /**< control intervals in the VIO journal */
uint32_t asmvt;
-};
+} zpage;
/**
* @brief Fill @p p from the ASMVT.
* @param p Where to write.
* @return false when this is not z/OS or there is no ASMVT.
*/
-bool zpage_read(struct zpage *p);
+bool zpage_read(zpage *p);
#endif
diff --git a/src/uss.c b/src/uss.c
new file mode 100644
index 0000000..2311c60
--- /dev/null
+++ b/src/uss.c
@@ -0,0 +1,172 @@
+/** @file uss.c
+ * @brief z/OS UNIX readers: mounted file systems and processes.
+ *
+ * w_getmntent() fills one contiguous header+entries buffer; statvfs() is
+ * then asked for the size and the read-only flag, so no mount-mode bit has
+ * to be decoded. w_getpsent() is a walk: token 0 is the first process and
+ * each call returns the token of the next one.
+ */
+#ifdef __MVS__
+#define _OPEN_SYS 1 /* sys/mntent.h, sys/ps.h */
+#define _OPEN_SYS_EXT 1 /* __errno2() */
+#endif
+
+#include "uss.h"
+
+#ifdef __MVS__
+#include <errno.h>
+#include <sys/mntent.h>
+#include <sys/ps.h>
+#include <sys/statvfs.h>
+#include <time.h> /* CLOCKS_PER_SEC */
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#ifdef __MVS__
+/** Copy at most @p n bytes of a name into @p dst, trimmed of blanks. */
+static void name_copy(char *dst, size_t len, const char *src, size_t n) {
+ size_t i = 0;
+
+ while (i < n && src[i] != '\0' && src[i] != ' ')
+ i++;
+ if (i >= len)
+ i = len - 1;
+ memcpy(dst, src, i);
+ dst[i] = '\0';
+}
+
+/** One w_getmntent() buffer: header, then the entries the service fills. */
+static struct {
+ MNTE3H h;
+ W_MNTENT3 e[USS_MAX_FS];
+} mnt;
+
+bool uss_fs_read(uss_fs_list *out) {
+ int n, i, fit;
+
+ memset(out, 0, sizeof *out);
+ memset(&mnt, 0, sizeof mnt);
+ memcpy(mnt.h.mnt3H_cbid, MNTE3H_ID, 4);
+ mnt.h.mnt3H_cblen = (int)sizeof mnt;
+ mnt.h.mnt3H_bodylen = (int)sizeof(W_MNTENT3);
+
+ n = w_getmntent((char *)&mnt, (int)sizeof mnt);
+ if (n < 0) {
+ (void)snprintf(out->err, sizeof out->err, "w_getmntent: errno %d",
+ errno);
+ return false;
+ }
+ /* The header length is the buffer size on the way in and what the
+ * service wrote on the way out; either can be smaller than the
+ * entries it reports, and a short one must not become a negative
+ * row count. */
+ fit = (int)((mnt.h.mnt3H_cblen - (int)sizeof(MNTE3H)) /
+ (int)sizeof(W_MNTENT3));
+ if (n == 0) /* some levels report the count only here */
+ n = fit;
+ if (fit < n)
+ n = fit;
+ if (n < 0)
+ n = 0;
+ out->truncated = n > USS_MAX_FS;
+ out->nfs = n > USS_MAX_FS ? USS_MAX_FS : n;
+
+ for (i = 0; i < out->nfs; i++) {
+ const W_MNTENT3 *e = &mnt.e[i];
+ uss_fs *f = &out->fs[i];
+ struct statvfs v;
+
+ name_copy(f->fsname, sizeof f->fsname, e->mnt3_fsname,
+ sizeof f->fsname);
+ name_copy(f->type, sizeof f->type, e->mnt3_fstname, sizeof f->type);
+ name_copy(f->mount, sizeof f->mount - 1, e->mnt3_mountpoint,
+ sizeof e->mnt3_mountpoint);
+ f->pct = -1;
+ if (statvfs(e->mnt3_mountpoint, &v) != 0) {
+ f->eno = errno;
+ continue;
+ }
+ f->ok = true;
+ f->rdonly = (v.f_flag & ST_RDONLY) != 0;
+ {
+ unsigned long unit = v.f_frsize ? v.f_frsize : v.f_bsize;
+ unsigned long long total = (unsigned long long)v.f_blocks * unit;
+ unsigned long long avail = (unsigned long long)v.f_bavail * unit;
+
+ f->kb_total = total / 1024;
+ f->kb_free = avail / 1024;
+ f->pct = total ? (int)((total - avail) * 100 / total) : -1;
+ }
+ }
+ return true;
+}
+
+bool uss_ps_read(uss_ps_list *out) {
+ int token = 0;
+
+ memset(out, 0, sizeof *out);
+ for (;;) {
+ W_PSPROC ps;
+ char tty[32], path[128], cmd[128];
+ int next;
+
+ if (out->nproc >= USS_MAX_PS) {
+ out->truncated = true;
+ break;
+ }
+ memset(&ps, 0, sizeof ps);
+ memset(tty, 0, sizeof tty);
+ memset(path, 0, sizeof path);
+ memset(cmd, 0, sizeof cmd);
+ ps.ps_conttylen = (int)sizeof tty;
+ ps.ps_conttyptr = tty;
+ ps.ps_pathlen = (int)sizeof path;
+ ps.ps_pathptr = path;
+ ps.ps_cmdlen = (int)sizeof cmd;
+ ps.ps_cmdptr = cmd;
+
+ next = w_getpsent(token, &ps, sizeof ps);
+ if (next == 0) /* no more processes this caller may see */
+ break;
+ if (next < 0) {
+ (void)snprintf(out->err, sizeof out->err, "w_getpsent: errno %d",
+ errno);
+ return out->nproc > 0;
+ }
+ token = next;
+
+ {
+ uss_proc *p = &out->proc[out->nproc];
+
+ p->pid = (int)ps.ps_pid;
+ p->ppid = (int)ps.ps_ppid;
+ p->uid = (int)ps.ps_euid; /* effective UID */
+ p->state = ps.ps_state;
+ p->st = (char)(ps.ps_state & PS_STATECHAR);
+ p->swapped = (ps.ps_state & PS_SWAP) != 0;
+ p->cpu_ms = (unsigned long)((ps.ps_usertime + ps.ps_systime) *
+ 1000 / CLOCKS_PER_SEC);
+ name_copy(p->tty, sizeof p->tty, tty, sizeof tty);
+ name_copy(p->cmd, sizeof p->cmd, cmd, sizeof cmd);
+ }
+ out->nproc++;
+ }
+ return true;
+}
+#else /* !__MVS__ */
+bool uss_fs_read(uss_fs_list *out) {
+ memset(out, 0, sizeof *out);
+ (void)snprintf(out->err, sizeof out->err,
+ "mounted file systems are only available on z/OS");
+ return false;
+}
+
+bool uss_ps_read(uss_ps_list *out) {
+ memset(out, 0, sizeof *out);
+ (void)snprintf(out->err, sizeof out->err,
+ "process data is only available on z/OS");
+ return false;
+}
+#endif /* __MVS__ */
diff --git a/src/uss.h b/src/uss.h
new file mode 100644
index 0000000..00245f7
--- /dev/null
+++ b/src/uss.h
@@ -0,0 +1,61 @@
+/** @file uss.h
+ * @brief z/OS UNIX readers: processes and mounted file systems.
+ *
+ * Two fixed-capacity tables filled in place. Neither reader allocates, and
+ * on a host that is not z/OS both report the same message the CVT readers
+ * print, so the portable build still links and the view stays honest.
+ */
+#ifndef ZTOP_USS_H
+#define ZTOP_USS_H
+
+#include <stdint.h>
+
+enum {
+ USS_MAX_FS = 64, /**< mounted file systems kept */
+ USS_MAX_PS = 128, /**< processes kept */
+};
+
+/** @brief One mounted file system, from w_getmntent() and statvfs(). */
+typedef struct uss_fs {
+ char fsname[45]; /**< aggregate data set name */
+ char mount[128]; /**< mount point, trimmed */
+ char type[9]; /**< file system type name */
+ bool rdonly; /**< statvfs says ST_RDONLY */
+ bool ok; /**< statvfs succeeded */
+ uint64_t kb_total;
+ uint64_t kb_free;
+ int pct; /**< 0..100, or -1 when the size is unknown */
+ int eno; /**< errno from a failed statvfs() */
+} uss_fs;
+
+typedef struct uss_fs_list {
+ uss_fs fs[USS_MAX_FS];
+ int nfs;
+ bool truncated;
+ char err[160];
+} uss_fs_list;
+
+/** @brief One process, from w_getpsent(). */
+typedef struct uss_proc {
+ int pid;
+ int ppid;
+ int uid;
+ unsigned state; /**< raw ps_state: letter in low bits, flags above */
+ char st; /**< the state letter, ps_state & PS_STATECHAR */
+ bool swapped;
+ unsigned long cpu_ms; /**< user + system time in milliseconds */
+ char tty[16];
+ char cmd[64];
+} uss_proc;
+
+typedef struct uss_ps_list {
+ uss_proc proc[USS_MAX_PS];
+ int nproc;
+ bool truncated;
+ char err[160];
+} uss_ps_list;
+
+bool uss_fs_read(uss_fs_list *out);
+bool uss_ps_read(uss_ps_list *out);
+
+#endif
diff --git a/src/vsm.c b/src/vsm.c
index aaeed1b..c396292 100644
--- a/src/vsm.c
+++ b/src/vsm.c
@@ -8,19 +8,19 @@
#include <stdio.h>
#include <string.h>
-struct rd {
+typedef struct rd {
const unsigned char *p;
unsigned len;
unsigned off;
bool bad;
-};
+} rd;
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(rd *r) {
if (r->bad || r->off > r->len || r->len - r->off < 4) {
r->bad = true;
return 0;
@@ -30,7 +30,7 @@ static uint32_t rd32(struct rd *r) {
return v;
}
-static unsigned rd8(struct rd *r) {
+static unsigned rd8(rd *r) {
if (r->bad || r->off >= r->len) {
r->bad = true;
return 0;
@@ -38,7 +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(vsm_info *v, const char *what, unsigned off) {
(void)snprintf(v->err, sizeof v->err, "%s at offset %u", what, off);
return false;
}
@@ -46,13 +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 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(vsm_info *v, unsigned area, unsigned space) {
memset(v, 0, sizeof *v);
v->area = area;
v->space = space;
@@ -70,7 +70,7 @@ bool vsm_work_data(const unsigned char *work, unsigned wlen,
dlen = be32(work + 8);
if (dlen == 0) {
- *data = NULL;
+ *data = nullptr;
*len = 0;
return true;
}
@@ -82,16 +82,15 @@ 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 vsm_subpool *sub_find(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];
if (v->nsub == VSM_MAX_SUB) {
v->truncated = true;
- return NULL;
+ return nullptr;
}
- struct vsm_subpool *s = &v->sub[v->nsub++];
+ vsm_subpool *s = &v->sub[v->nsub++];
memset(s, 0, sizeof *s);
s->id = id;
s->tcb = tcb;
@@ -101,8 +100,7 @@ static struct vsm_subpool *sub_find(struct vsm_info *v, unsigned id,
/* 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(rd *r, vsm_info *v, vsm_subpool *s) {
unsigned off = r->off;
uint32_t addr = rd32(r);
uint32_t blen = rd32(r);
@@ -136,6 +134,11 @@ static bool parse_block(struct rd *r, struct vsm_info *v,
v->foot += blen;
v->free += bfree;
v->used += used;
+ /* A block is counted on the side of the line its first byte is on. */
+ if (addr < VSM_LINE_16M)
+ v->below += used;
+ else
+ v->above += used;
if (blen > v->largest)
v->largest = blen;
if (addr < v->lo)
@@ -143,11 +146,15 @@ static bool parse_block(struct rd *r, struct vsm_info *v,
if ((uint64_t)addr + blen > v->hi)
v->hi = (uint32_t)((uint64_t)addr + blen);
- if (s != NULL) {
+ if (s != nullptr) {
s->blocks++;
s->foot += blen;
s->free += bfree;
s->used += used;
+ if (addr < VSM_LINE_16M)
+ s->below += used;
+ else
+ s->above += used;
if (blen > s->largest)
s->largest = blen;
if (addr < s->lo)
@@ -158,7 +165,7 @@ static bool parse_block(struct rd *r, struct vsm_info *v,
return true;
}
-static bool parse_alloc_section(struct rd *r, struct vsm_info *v) {
+static bool parse_alloc_section(rd *r, vsm_info *v) {
uint32_t nsub = rd32(r);
if (r->bad)
return fail(v, "subpool count past end of data", r->off - 4);
@@ -192,8 +199,8 @@ static bool parse_alloc_section(struct rd *r, struct vsm_info *v) {
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);
- if (s != NULL) {
+ vsm_subpool *s = sub_find(v, id, v->area == VSM_PVT ? tcb : 0);
+ if (s != nullptr) {
s->key = flags & 0x0Fu;
s->flags = flags;
}
@@ -204,9 +211,8 @@ 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(vsm_info *v, const unsigned char *data, unsigned len) {
+ rd r = {data, len, 0, false};
if (v->area == VSM_PVT) {
uint32_t n = rd32(&r);
@@ -229,9 +235,8 @@ bool vsm_parse_alloc(struct vsm_info *v, const unsigned char *data,
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(vsm_info *v, const unsigned char *data, unsigned len) {
+ rd r = {data, len, 0, false};
uint32_t nreg = rd32(&r);
if (r.bad)
diff --git a/src/vsm.h b/src/vsm.h
index b762788..ae17a1a 100644
--- a/src/vsm.h
+++ b/src/vsm.h
@@ -10,7 +10,6 @@
#ifndef ZTOP_VSM_H
#define ZTOP_VSM_H
-#include <stdbool.h>
#include <stdint.h>
/** @brief Area codes, the same numbers the assembler stub takes. */
@@ -20,42 +19,49 @@ enum vsm_area { VSM_CSA = 1, VSM_SQA = 2, VSM_LSQA = 3, VSM_PVT = 4 };
enum vsm_space { VSM_FREE = 1, VSM_UNALLOC = 2 };
/** @brief Rows kept per area; PVT can hold several TCBs of subpools. */
-#define VSM_MAX_SUB 512
+enum { VSM_MAX_SUB = 512 };
/** @brief Region descriptors kept for display (CSA/ECSA/RUCSA, PVT regions). */
-#define VSM_MAX_REGION 16
+enum { VSM_MAX_REGION = 16 };
+
+/** @brief The 16-megabyte line: below it are 24-bit addresses. */
+enum { VSM_LINE_16M = 0x01000000 };
/** @brief One subpool: allocated blocks, the free space in them, the real use.
*/
-struct vsm_subpool {
+typedef 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 below; /**< used bytes in blocks starting below the 16M line */
+ uint64_t above; /**< used bytes in blocks starting at or above 16M */
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 */
-};
+} vsm_subpool;
/** @brief A region descriptor (an unallocated range, or a PVT region). */
-struct vsm_region {
+typedef struct vsm_region {
uint32_t addr;
uint32_t len;
-};
+} vsm_region;
/** @brief Everything one area reports, accumulated over continuation calls. */
-struct vsm_info {
+typedef struct vsm_info {
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];
+ vsm_subpool sub[VSM_MAX_SUB];
unsigned blocks; /**< allocated blocks in the area */
uint64_t used;
+ uint64_t below; /**< used bytes in blocks starting below the 16M line */
+ uint64_t above; /**< used bytes in blocks starting at or above 16M */
uint64_t free;
uint64_t foot;
uint64_t largest;
@@ -65,15 +71,15 @@ struct vsm_info {
uint64_t unalloc; /**< unallocated bytes (CSA/PVT only) */
uint64_t largest_unalloc;
int nregion;
- struct vsm_region region[VSM_MAX_REGION];
+ vsm_region region[VSM_MAX_REGION];
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 */
-};
+} vsm_info;
/** @brief Zero @p v and set the request it describes. */
-void vsm_reset(struct vsm_info *v, unsigned area, unsigned space);
+void vsm_reset(vsm_info *v, unsigned area, unsigned space);
/**
* @brief Check the work-area header and locate the data area.
@@ -95,11 +101,9 @@ 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(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(vsm_info *v, const unsigned char *data, unsigned len);
#endif
diff --git a/src/zmcs.c b/src/zmcs.c
new file mode 100644
index 0000000..3473724
--- /dev/null
+++ b/src/zmcs.c
@@ -0,0 +1,22 @@
+/**
+ * @file zmcs.c
+ * @brief The portable half of the console reader: there is none.
+ *
+ * The console lives in src/zmcs.s, which is built only on z/OS. The
+ * tests and the portable build still link the symbol, so this file
+ * answers "no" instead of letting the link fail. It is deliberately
+ * the only thing here: a fake console would let a change look tested.
+ */
+#include "zmcs.h"
+
+#ifndef __MVS__
+
+int zmcs(zmcs_req *req) {
+ req->rc = 8;
+ req->rsn = 0;
+ if (req->len != nullptr)
+ *req->len = 0;
+ return 0;
+}
+
+#endif /* !__MVS__ */
diff --git a/src/zmcs.h b/src/zmcs.h
new file mode 100644
index 0000000..4ad870c
--- /dev/null
+++ b/src/zmcs.h
@@ -0,0 +1,73 @@
+/**
+ * @file zmcs.h
+ * @brief Extended MCS console: the one service that needs supervisor
+ * state.
+ *
+ * MCSOPER and MCSOPMSG both require supervisor state (SA22-7614-..,
+ * "MCSOPER - Environment": minimum authorization supervisor state and
+ * any PSW key), and MCSOPMSG also wants access-register mode, so the
+ * calls live in src/zmcs.s: it switches to
+ * supervisor state, calls the macro, switches back, and hands the
+ * caller a copy of the message data block (MDB, IEAVM105, 160 bytes
+ * plus text). Nothing else in ztop needs a privileged instruction.
+ *
+ * The alternative, an EMCS console opened through an authorized
+ * caller, is what this is: the program must be marked APF
+ * (`extattr +ap ./ztop`, Makefile target `auth`) and the user needs
+ * READ on MVS.MCSOPER.consname.
+ *
+ * The stub builds the MCSOPER/MODESET control blocks in its own CSECT, so
+ * it is a 31-bit module of its own: an assembler CSECT linked into an
+ * XPLINK program object is read-only, and the macros store into those
+ * blocks (measured on CBT, 2026-11-27). See the header of src/zmcs.s.
+ *
+ * The offsets in zmcs_req are the stub's interface and are checked in
+ * src/ztop.c. Keep the two in step.
+ */
+#ifndef ZTOP_ZMCS_H
+#define ZTOP_ZMCS_H
+
+#include <stdint.h>
+
+/** Operations for zmcs_req.op. */
+enum zmcs_op {
+ ZMCS_ACTIVATE = 0, /**< open the console, fills consid */
+ ZMCS_GETMSG = 1, /**< one message into buf, length in len */
+ ZMCS_DEACTIVATE = 2, /**< close the console */
+};
+
+/**
+ * @brief The request block the stub reads and writes.
+ *
+ * All pointers are 31-bit: the program is built -m32, so every object
+ * it owns is reachable from an AMODE 31 assembler routine.
+ */
+typedef struct zmcs_req {
+ int op; /**< 0: one of enum zmcs_op */
+ char *name; /**< 4: 8 byte console name, blank padded */
+ unsigned *consid; /**< 8: console id, out */
+ char *buf; /**< 12: MDB copy destination */
+ int *len; /**< 16: in capacity, out copied */
+ int rc; /**< 20: service return code */
+ int rsn; /**< 24: service reason code */
+ unsigned char ecb[4]; /**< 28: MSGECB, posted on a message */
+ unsigned alet; /**< 32: MCSCSAA: ALET, from the service */
+ unsigned long long save[18]; /**< 40: the stub's save area */
+ void *csa; /**< 184: MCSCSA: status area, from it */
+} zmcs_req;
+
+/** Largest MDB we copy out of the console's data space. */
+enum { ZMCS_MDB_MAX = 4096 };
+
+#ifdef __MVS__
+/* HLASM upcases the ESD name of the CSECT, so the assembler side is
+ * exported as ZMCS whatever case the source is written in, and the C
+ * side has to ask for that name. The stub is not XPLINK, so the call
+ * uses the OS linkage convention, exactly like src/zvslist.S. */
+int zmcs(zmcs_req *req) __asm__("ZMCS");
+#pragma linkage(zmcs, OS)
+#else
+int zmcs(zmcs_req *req);
+#endif
+
+#endif /* ZTOP_ZMCS_H */
diff --git a/src/zmcs.s b/src/zmcs.s
new file mode 100644
index 0000000..c239c5f
--- /dev/null
+++ b/src/zmcs.s
@@ -0,0 +1,185 @@
+*
+* zmcs -- the extended MCS console. MCSOPER and MCSOPMSG both need
+* supervisor state (SA22-7614 "Environment": supervisor state, any PSW
+* key) and MCSOPMSG also wants access-register mode.
+*
+* The caller fills a zmcs_req (src/zmcs.h) and calls zmcs() with it.
+* The offsets below are that block, -m32, asserted by the C side.
+*
+* Module rule: MODESET and MCSOPER build their control blocks here and
+* store into them at run time, so this has to be a 31-bit module of its
+* own, reached through a thunk. An assembler CSECT linked into an
+* XPLINK program object is read-only and that store is a 0C4.
+*
+zmcs CSECT
+zmcs AMODE 31
+zmcs RMODE 24
+*
+* Request block offsets (src/zmcs.h).
+ZR_OP EQU 0 int op
+ZR_NAME EQU 4 char *name
+ZR_CONS EQU 8 unsigned *consid, out
+ZR_BUF EQU 12 char *buf
+ZR_LEN EQU 16 int *len, in capacity, out count
+ZR_RC EQU 20 int rc
+ZR_RSN EQU 24 int rsn
+ZR_ECB EQU 28 unsigned char ecb[4], MSGECB
+ZR_ALET EQU 32 unsigned alet, out, MCSCSAA
+ZR_SAVE EQU 40 save area, 18 fullwords
+ZR_CSA EQU 184 void *csa, out, MCSCSA
+*
+* Operations (enum zmcs_op).
+ZOP_ACT EQU 0
+ZOP_GET EQU 1
+ZOP_DEA EQU 2
+*
+ STM R14,R12,12(R13)
+ BALR R12,R0
+ USING *,R12
+ LAE R12,R0(R0,R12) AR12 = 0: our own storage
+ L R2,0(R1) R1 -> list, word 0 = the request
+ LTR R2,R2
+ BZ BADREQ
+ LAE R11,R0(R0,R2) AR11 = 0 too
+ LA R10,ZR_SAVE(,R11) save area, inside the request
+ ST R13,4(,R10) the caller's, for a dump
+ ST R10,8(,R13)
+ LR R13,R10
+ L R3,ZR_OP(,R11)
+ CHI R3,ZOP_ACT
+ BE DOACT
+ CHI R3,ZOP_GET
+ BE DOGET
+ CHI R3,ZOP_DEA
+ BE DODEACT
+ LA R3,4 unknown request
+ B BACK
+*
+* ACTIVATE, in primary space mode: MCSOPER does not need AR mode.
+* MCSCSA and MCSCSAA are output areas: the service writes the address
+* of the console status area and its ALET there. QLIMIT bounds the
+* queue, so a console left open cannot grow until storage runs out.
+*
+DOACT DS 0H
+ MODESET MODE=SUP
+ LTR R15,R15
+ BNZ NORIGHTS
+ L R5,ZR_NAME(,R11) NAME and TERMNAME
+ L R6,ZR_CONS(,R11) CONSID, out
+ L R4,ZR_CSA(,R11) MCSCSA, out
+ L R3,ZR_ALET(,R11) MCSCSAA, out
+ LHI R9,ZMCS_QLIMIT
+ MCSOPER REQUEST=ACTIVATE, X
+ NAME=(R5), X
+ TERMNAME=(R5), X
+ MSGDLVRY=FIFO, X
+ MSGECB=ZR_ECB(,R11), X
+ MCSCSA=(R4), X
+ MCSCSAA=(R3), X
+ CONSID=(R6), X
+ QLIMIT=(R9), X
+ RTNCODE=ZR_RC(,R11), X
+ RSNCODE=ZR_RSN(,R11)
+ MODESET MODE=PROB
+ B BACKRC
+*
+* GETMSG. The service wants AR mode and hands back the MDB address in
+* R1 with its ALET in AR1. The MDB lies in the console's data space,
+* so it is copied out here, still in AR mode. RC 8 is "nothing
+* queued", the steady state.
+*
+DOGET DS 0H
+ SAC 0 primary mode for MODESET
+ MODESET MODE=SUP
+ LTR R15,R15
+ BNZ NORIGHTS
+ SAC 512 AR mode for MCSOPMSG
+ SYSSTATE ASCENV=AR
+ L R6,ZR_CONS(,R11)
+ MCSOPMSG REQUEST=GETMSG, X
+ CONSID=(R6), X
+ RTNCODE=ZR_RC(,R11), X
+ RSNCODE=ZR_RSN(,R11)
+ CHI R15,0
+ BE DOCOPY
+ CHI R15,ZMCS_RC_QUEUED
+ BNE GETEND
+DOCOPY DS 0H
+ LAE R8,0(R0,R1) R8 = MDB, AR8 = the MDB's ALET
+ LH R4,0(,R8) MDBLEN, the first halfword
+ L R5,ZR_LEN(,R11) capacity the caller offered
+ CR R4,R5
+ BNH COPYOK
+ LR R4,R5 clip
+COPYOK DS 0H
+ ST R4,ZR_LEN(,R11) length copied
+ L R3,ZR_BUF(,R11)
+ LAE R3,0(R0,R3) AR3 = 0: our own space
+ LTR R4,R4
+ BZ GETEND
+CLOOP DS 0H
+ MVC 0(1,R3),0(R8)
+ LA R3,1(,R3)
+ LA R8,1(,R8)
+ BCT R4,CLOOP
+GETEND DS 0H
+ SAC 0 primary mode for MODESET
+ SYSSTATE ASCENV=P
+ MODESET MODE=PROB
+ B BACKRC
+*
+* DEACTIVATE: hand the console id back.
+*
+DODEACT DS 0H
+ MODESET MODE=SUP
+ LTR R15,R15
+ BNZ NORIGHTS
+ L R6,ZR_CONS(,R11)
+ MCSOPER REQUEST=DEACTIVATE, X
+ CONSID=(R6), X
+ RTNCODE=ZR_RC(,R11), X
+ RSNCODE=ZR_RSN(,R11)
+ MODESET MODE=PROB
+ B BACKRC
+*
+* Returns. NORIGHTS is the MODESET refusal: an unauthorized program
+* never gets here, the restricted SVC ends the task with S047.
+*
+NORIGHTS DS 0H
+ ST R15,ZR_RSN(,R11) the MODESET reason
+ LA R3,12
+ ST R3,ZR_RC(,R11)
+ B BACK
+BADREQ DS 0H
+ LA R3,4
+ B BACK
+BACKRC DS 0H
+ L R3,ZR_RC(,R11)
+BACK DS 0H
+ LR R2,R11
+ L R13,4(,R13)
+ LM R14,R12,12(R13)
+ BR R14
+*
+* Constants.
+ZMCS_QLIMIT EQU 2000 messages the console may queue
+ZMCS_RC_QUEUED EQU 4 message returned, queueing suspended
+*
+* Registers, by name, so a number is never read as a register.
+R0 EQU 0
+R1 EQU 1
+R2 EQU 2
+R3 EQU 3
+R4 EQU 4
+R5 EQU 5
+R6 EQU 6
+R7 EQU 7
+R8 EQU 8
+R9 EQU 9
+R10 EQU 10
+R11 EQU 11
+R12 EQU 12
+R13 EQU 13
+R14 EQU 14
+R15 EQU 15
+ END
diff --git a/src/ztop.c b/src/ztop.c
index 31039c2..458362f 100644
--- a/src/ztop.c
+++ b/src/ztop.c
@@ -6,7 +6,7 @@
* view is built on libtui, which knows nothing about z/OS: ztop supplies
* the model, the messages and the tables.
*/
-#include <stdbool.h>
+#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
@@ -17,11 +17,29 @@
#include <unistd.h>
#include "sys.h"
+#include "mdb.h"
+#include "uss.h"
#include "tui.h"
#include "vsm.h"
+#include "zmcs.h"
-#define ZTOP_VERSION "0.3"
-#define WORK_SIZE (1024u * 1024u)
+static const char ZTOP_VERSION[] = "0.3";
+
+/* The console is opt-in: opening it calls MODESET, and an unauthorized
+ * program does not get a return code from that, it gets S047. */
+static bool console_opt;
+
+/* The stub in src/zmcs.s addresses these fields by offset, and those are
+ * the -m32 offsets: a pointer is 4 bytes there, so the same struct on a
+ * 64-bit host has a different shape and the check would only be noise. */
+#if defined(__MVS__)
+static_assert(offsetof(zmcs_req, save) == 40, "zmcs_req.save");
+static_assert(offsetof(zmcs_req, csa) == 184, "zmcs_req.csa");
+static_assert(offsetof(zmcs_req, alet) == 32, "zmcs_req.alet");
+static_assert(offsetof(zmcs_req, ecb) == 28, "zmcs_req.ecb");
+static_assert(offsetof(zmcs_req, rsn) == 24, "zmcs_req.rsn");
+static_assert(sizeof(zmcs_req) == 188, "zmcs_req: runs into the next object");
+#endif
#if defined(__MVS__)
/* HLASM upcases the ESD name of the CSECT, so the assembler side is
@@ -32,7 +50,7 @@ extern int zvslist(void *) __asm__("ZVSLIST");
/* 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 {
+typedef struct zreq {
int area;
unsigned len;
void *wk;
@@ -40,11 +58,12 @@ struct zreq {
void *self;
unsigned long long save[18];
int space;
-};
-_Static_assert(offsetof(struct zreq, self) == 16, "zreq.self");
-_Static_assert(offsetof(struct zreq, save) == 24, "zreq.save");
-_Static_assert(offsetof(struct zreq, space) == 168, "zreq.space");
+} zreq;
+static_assert(offsetof(zreq, self) == 16, "zreq.self");
+static_assert(offsetof(zreq, save) == 24, "zreq.save");
+static_assert(offsetof(zreq, space) == 168, "zreq.space");
+static constexpr unsigned WORK_SIZE = 1024 * 1024;
static unsigned char work[WORK_SIZE] __attribute__((aligned(8)));
#endif
@@ -78,18 +97,18 @@ static void hexdump(const char *tag, const unsigned char *p, unsigned int len,
}
}
-static void dump_work(const struct vsm_info *v, const unsigned char *workp,
+static void dump_work(const vsm_info *v, const unsigned char *workp,
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 int)(uintptr_t)data, len);
hexdump("work", workp, 32, 32);
- if (data != NULL && len > 0)
+ if (data != nullptr && len > 0)
hexdump("data", data, len, 256);
}
-static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) {
+static bool fetch_one(vsm_info *v, int area, int space, bool dump) {
int calls = 0;
const unsigned char *data;
unsigned int len;
@@ -97,7 +116,7 @@ static bool fetch_one(struct vsm_info *v, int area, int space, bool dump) {
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};
+ zreq req = {0};
bool ok;
if (++calls > 64) {
@@ -133,7 +152,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(vsm_info *v, int area, int space, bool dump) {
(void)area;
(void)space;
(void)dump;
@@ -142,11 +161,11 @@ 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(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;
+ vsm_info u;
if (fetch_one(&u, area, VSM_UNALLOC, dump)) {
v->unalloc = u.unalloc;
@@ -164,11 +183,11 @@ static bool collect_area(struct vsm_info *v, int area, bool dump) {
/** @brief Fraction of the mapped area in use, or -1 when there is no total. */
/* Only CSA and PVT get an unallocated pass, so only they have a total. */
-static bool has_total(const struct vsm_info *v) {
+static bool has_total(const vsm_info *v) {
return (v->area == VSM_CSA || v->area == VSM_PVT) && v->unalloc_valid;
}
-static int pct(const struct vsm_info *v) {
+static int pct(const vsm_info *v) {
uint64_t total;
if (!has_total(v))
@@ -179,15 +198,18 @@ static int pct(const struct vsm_info *v) {
return (int)((v->used * 100u + total / 2) / total);
}
-static void print_area(const struct vsm_info *v) {
+static void print_area(const 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,
- (unsigned long long)v->foot, v->blocks);
+ (void)printf("area %s: used %llu (below 16M %llu above 16M %llu) free %llu "
+ "mapped %llu blocks %u",
+ name, (unsigned long long)v->used,
+ (unsigned long long)v->below, (unsigned long long)v->above,
+ (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%%",
(unsigned long long)v->unalloc,
@@ -205,7 +227,7 @@ static void print_area(const struct vsm_info *v) {
"blks", "used", "free", "mapped", "largest", "address");
for (i = 0; i < v->nsub; i++) {
- const struct vsm_subpool *s = &v->sub[i];
+ const vsm_subpool *s = &v->sub[i];
char addr[32];
if (s->blocks == 0)
@@ -246,7 +268,7 @@ static void print_area(const struct vsm_info *v) {
(void)printf("warning: %s\n", v->err);
}
-static void print_system(const struct zsys *z) {
+static void print_system(const 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);
@@ -257,7 +279,7 @@ static void print_system(const struct zsys *z) {
(unsigned long long)z->real_k);
}
-static void print_page(const struct zpage *p) {
+static void print_page(const zpage *p) {
(void)printf("aux storage common %s%s plpa %s%s local %s vio %s"
", journal %u\n",
p->common_pds ? "yes" : "no", p->common_full ? " full" : "",
@@ -266,7 +288,7 @@ static void print_page(const struct zpage *p) {
p->vio_journaling ? "on" : "off", p->vio_ci);
}
-static void print_jobs(const struct zsys *z) {
+static void print_jobs(const zsys *z) {
int i;
(void)printf("%4s %-8s %8s\n", "asid", "job", "ascb");
@@ -275,14 +297,26 @@ static void print_jobs(const struct zsys *z) {
(unsigned int)z->job[i].ascb);
}
-struct app {
- struct vsm_info info[4];
+typedef struct pvt_row {
+ uint32_t tcb;
+ unsigned nsub;
+ uint64_t used;
+ uint64_t below;
+ uint64_t above;
+} pvt_row;
+
+/* The console ring: 256 lines of 200 columns is 51K inside the model,
+ * and it never grows. */
+enum { LOG_LINES = 256, LOG_COLS = 200 };
+
+typedef struct app {
+ vsm_info info[4];
bool have[4];
char err[4][160];
- struct zsys sys;
+ zsys sys;
bool have_sys;
char sys_err[160];
- struct zpage page;
+ zpage page;
bool have_page;
char page_err[160];
int interval;
@@ -291,16 +325,50 @@ struct app {
bool help;
int tab;
int sub;
- struct tui_table storage;
- struct tui_table jobs;
- struct tui_app *tapp;
+ tui_table storage;
+ tui_table jobs;
+ tui_app *tapp;
char host[65];
int sub_sort, sub_dir;
int job_sort, job_dir;
int sub_order[VSM_MAX_SUB];
int job_order[ZJOB_MAX];
bool popup;
-};
+ bool pvt_fold;
+ bool tcb_popup;
+ bool inspector;
+ char filter[32];
+ tui_input fin;
+ tui_input cin;
+ bool filtering;
+ bool commanding;
+ int sub_rows;
+ int job_rows;
+ unsigned char trend[4][32]; /* per-area use%, newest last */
+ int ntrend[4];
+ tui_viewport pvt_vp;
+ pvt_row pvt[VSM_MAX_SUB];
+ int npvt;
+ uss_ps_list ps;
+ uss_fs_list fs;
+ bool have_ps;
+ bool have_fs;
+ tui_table pst;
+ tui_table fst;
+ /* The console log: one request block, one ring of lines, both in the
+ * model, because a refresh must not allocate. */
+ zmcs_req creq;
+ char creq_name[8];
+ unsigned creq_consid;
+ char mdb[ZMCS_MDB_MAX];
+ int mdb_len;
+ char log[LOG_LINES][LOG_COLS];
+ int nlog;
+ int log_next;
+ bool log_on;
+ char log_err[160];
+ tui_viewport log_vp;
+} app;
enum { SS_SP, SS_KEY, SS_BLOCKS, SS_USED, SS_FREE, SS_LARGEST, SS_COUNT };
enum { JS_ASID, JS_JOB, JS_ADDR, JS_COUNT };
@@ -312,13 +380,141 @@ static const char *const job_sort_names[JS_COUNT] = {"asid", "job", "ascb"};
/* qsort has no context argument; these are set right before each call and
* the application is single-threaded. */
-static const struct vsm_info *sort_info;
-static const struct zsys *sort_sys;
+static const vsm_info *sort_info;
+static const zsys *sort_sys;
static int sort_key, sort_dir;
static int cmp_u64(uint64_t a, uint64_t b) {
return (a > b) - (a < b);
}
+/* ---- the folded PVT view: one row per TCB ---- */
+
+/* Defined with the filter, needed by the folded table and by collect. */
+static bool match(const char *hay, const char *pat);
+static void order_storage(app *a);
+
+/* Defined below; the tick and the command bar use them. */
+static void log_start(app *a);
+static void log_poll(app *a);
+static void log_stop(app *a);
+
+/* The console is named after the caller, so two people (or two sessions)
+ * do not collide on one name and the RACF profile can be that user's
+ * alone. The service checks MVS.MCSOPER.<name>, so the name is not a
+ * secret: an unauthorised user choosing someone else's name is refused. */
+static void console_name(char *name) {
+ const char *from = getenv("LOGNAME");
+
+ if (from == nullptr || *from == '\0')
+ from = getenv("USER");
+ (void)memset(name, ' ', 8);
+ if (from == nullptr)
+ from = "ZTOP";
+ for (int i = 0; i < 8 && from[i] != '\0'; i++) {
+ unsigned char c = (unsigned char)from[i];
+
+ if (c >= 'a' && c <= 'z')
+ c = (unsigned char)(c - 'a' + 'A');
+ name[i] =
+ (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ? (char)c : '_';
+ }
+}
+
+static int tcb_order[VSM_MAX_SUB];
+
+static int cmp_tcb(const void *pa, const void *pb) {
+ const vsm_subpool *a = &sort_info->sub[*(const int *)pa];
+ const vsm_subpool *b = &sort_info->sub[*(const int *)pb];
+
+ return (a->tcb > b->tcb) - (a->tcb < b->tcb);
+}
+
+/* Group the subpools by owning TCB. Sorted first, so the grouping is a
+ * linear pass and the row table needs no allocation. */
+static void build_pvt(app *a) {
+ const vsm_info *v = &a->info[3];
+
+ a->npvt = 0;
+ if (!a->have[3])
+ return;
+ for (int i = 0; i < v->nsub; i++)
+ tcb_order[i] = i;
+ sort_info = v;
+ qsort(tcb_order, (size_t)v->nsub, sizeof tcb_order[0], cmp_tcb);
+ for (int i = 0; i < v->nsub; i++) {
+ const vsm_subpool *s = &v->sub[tcb_order[i]];
+ pvt_row *r;
+
+ if (a->npvt > 0 && a->pvt[a->npvt - 1].tcb == s->tcb) {
+ r = &a->pvt[a->npvt - 1];
+ } else {
+ if (a->npvt >= VSM_MAX_SUB)
+ break;
+ r = &a->pvt[a->npvt++];
+ *r = (pvt_row){s->tcb, 0, 0, 0, 0};
+ }
+ r->nsub++;
+ r->used += s->used;
+ r->below += s->below;
+ r->above += s->above;
+ }
+ {
+ int n = 0;
+
+ for (int i = 0; i < a->npvt; i++) {
+ char key[16];
+
+ (void)snprintf(key, sizeof key, "%08X",
+ (unsigned int)a->pvt[i].tcb);
+ if (match(key, a->filter))
+ a->pvt[n++] = a->pvt[i];
+ }
+ a->npvt = n;
+ }
+}
+
+/* The viewport and row count the keys act on, so a folded PVT and the JOBS
+ * table never need their own copy of the movement code. */
+static bool folded(const app *a) {
+ return a->tab == 0 && a->sub == 3 && a->pvt_fold;
+}
+
+static tui_viewport *vp_of(app *a) {
+ if (folded(a))
+ return &a->pvt_vp;
+ if (a->tab == 2)
+ return &a->jobs.vp;
+ if (a->tab == 4)
+ return &a->pst.vp;
+ if (a->tab == 5)
+ return &a->fst.vp;
+ if (a->tab == 6)
+ return &a->log_vp;
+ return &a->storage.vp;
+}
+
+static int vrows(const app *a) {
+ if (folded(a))
+ return a->npvt;
+ if (a->tab == 2)
+ return a->job_rows;
+ if (a->tab == 4)
+ return a->ps.nproc;
+ if (a->tab == 5)
+ return a->fs.nfs;
+ if (a->tab == 6)
+ return a->nlog;
+ return a->sub_rows;
+}
+
+static int vheight(const app *a, int h) {
+ if (a->tab == 0)
+ return h - 8;
+ if (a->tab == 2 || a->tab == 4 || a->tab == 5 || a->tab == 6)
+ return h - 6;
+ return 0;
+}
+
static int cmp_u32(uint32_t a, uint32_t b) {
return (a > b) - (a < b);
}
@@ -326,8 +522,8 @@ static int cmp_u32(uint32_t a, uint32_t b) {
static int cmp_sub(const void *pa, const void *pb) {
int ia = *(const int *)pa;
int ib = *(const int *)pb;
- const struct vsm_subpool *a = &sort_info->sub[ia];
- const struct vsm_subpool *b = &sort_info->sub[ib];
+ const vsm_subpool *a = &sort_info->sub[ia];
+ const vsm_subpool *b = &sort_info->sub[ib];
int r = 0;
switch (sort_key) {
@@ -356,8 +552,8 @@ static int cmp_sub(const void *pa, const void *pb) {
static int cmp_job(const void *pa, const void *pb) {
int ia = *(const int *)pa;
int ib = *(const int *)pb;
- const struct zjob *a = &sort_sys->job[ia];
- const struct zjob *b = &sort_sys->job[ib];
+ const zjob *a = &sort_sys->job[ia];
+ const zjob *b = &sort_sys->job[ib];
int r = 0;
switch (sort_key) {
@@ -374,28 +570,68 @@ static int cmp_job(const void *pa, const void *pb) {
return r != 0 ? sort_dir * r : ia - ib;
}
-static const struct tui_col storage_cols[] = {
+static const tui_col storage_cols[] = {
{"SP", 3, true}, {"KY", 3, true}, {"BLKS", 8, true},
{"USED", 10, true}, {"FREE", 10, true}, {"MAPPED", 10, true},
{"LARGEST", 10, true}, {"ADDRESS", 17, false},
};
-static const struct tui_col pvt_cols[] = {
+static const tui_col pvt_cols[] = {
{"SP", 3, true}, {"KY", 3, true}, {"BLKS", 7, true},
{"USED", 10, true}, {"FREE", 10, true}, {"MAPPED", 10, true},
{"LARGEST", 10, true}, {"TCB", 9, false},
};
-static const struct tui_col job_cols[] = {
+/* The folded PVT table: one row per TCB, with the 16M split and which side
+ * of the line the TCB's storage is on. */
+static const tui_col pvt_fold_cols[] = {
+ {"TCB", 9, false}, {"SUBS", 5, true}, {"USED", 10, true},
+ {"<16M", 10, true}, {">16M", 10, true}, {"LINE", 5, false},
+};
+
+static const tui_col job_cols[] = {
{"ASID", 6, true},
{"JOB", 9, false},
{"ASCB", 10, false},
};
+static void pvt_cell(void *ctx, int row, int col, char *buf, size_t len) {
+ const app *a = ctx;
+ const pvt_row *r = &a->pvt[row];
+ char u[16], b[16], ab[16];
+
+ switch (col) {
+ case 0:
+ (void)snprintf(buf, len, "%08X", (unsigned int)r->tcb);
+ break;
+ case 1:
+ (void)snprintf(buf, len, "%u", r->nsub);
+ break;
+ case 2:
+ human(r->used, u, sizeof u);
+ (void)snprintf(buf, len, "%s", u);
+ break;
+ case 3:
+ human(r->below, b, sizeof b);
+ (void)snprintf(buf, len, "%s", b);
+ break;
+ case 4:
+ human(r->above, ab, sizeof ab);
+ (void)snprintf(buf, len, "%s", ab);
+ break;
+ default:
+ (void)snprintf(buf, len, "%s",
+ r->below != 0 && r->above != 0 ? "BOTH"
+ : r->above != 0 ? ">16M"
+ : "<16M");
+ break;
+ }
+}
+
static void storage_cell(void *ctx, int row, int col, char *buf, size_t len) {
- const struct app *a = ctx;
- int i = row < a->info[a->sub].nsub ? a->sub_order[row] : row;
- const struct vsm_subpool *s = &a->info[a->sub].sub[i];
+ const app *a = ctx;
+ int i = row < a->sub_rows ? a->sub_order[row] : row;
+ const vsm_subpool *s = &a->info[a->sub].sub[i];
char u[16], f[16], m[16], l[16];
switch (col) {
@@ -437,9 +673,9 @@ static void storage_cell(void *ctx, int row, int col, char *buf, size_t len) {
}
static void job_cell(void *ctx, int row, int col, char *buf, size_t len) {
- const struct app *a = ctx;
- int i = row < a->sys.njobs ? a->job_order[row] : row;
- const struct zjob *j = &a->sys.job[i];
+ const app *a = ctx;
+ int i = row < a->job_rows ? a->job_order[row] : row;
+ const zjob *j = &a->sys.job[i];
switch (col) {
case 0:
@@ -454,8 +690,8 @@ static void job_cell(void *ctx, int row, int col, char *buf, size_t len) {
}
}
-static void sys_read(struct app *a) {
- struct zsys z;
+static void sys_read(app *a) {
+ zsys z;
struct utsname u;
(void)memcpy(&z, &a->sys, sizeof z);
@@ -475,13 +711,28 @@ static void sys_read(struct app *a) {
a->sys_err[0] = '\0';
}
-static void collect(struct app *a) {
+/* Keep the last 32 samples of an area's use%, so the storage view can draw
+ * its recent shape without keeping history anywhere else. */
+static void push_trend(app *a, int i, int p) {
+ unsigned char *t = a->trend[i];
+ int *n = &a->ntrend[i];
+
+ if (p < 0 || p > 100)
+ return;
+ if (*n == (int)sizeof a->trend[i]) {
+ (void)memmove(t, t + 1, sizeof a->trend[i] - 1);
+ (*n)--;
+ }
+ t[(*n)++] = (unsigned char)p;
+}
+
+static void collect(app *a) {
struct timespec t0, t1;
int i;
(void)clock_gettime(CLOCK_MONOTONIC, &t0);
for (i = 0; i < 4; i++) {
- struct vsm_info v;
+ vsm_info v;
if (collect_area(&v, i + 1, false)) {
a->info[i] = v;
@@ -496,37 +747,89 @@ static void collect(struct app *a) {
if (!a->have_page)
(void)snprintf(a->page_err, sizeof a->page_err,
"ASMVT is only available on z/OS");
+ build_pvt(a);
+ order_storage(a);
+ if (a->tab == 4)
+ a->have_ps = uss_ps_read(&a->ps);
+ else if (a->tab == 5)
+ a->have_fs = uss_fs_read(&a->fs);
+ log_poll(a);
+ for (i = 0; i < 4; i++)
+ if (a->have[i])
+ push_trend(a, i, pct(&a->info[i]));
(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 const struct tui_hint view_bar[] = {
- {"q", "quit"},
- {"TAB", "view"},
- {"r", "refresh"},
- {"?", "help"},
+/* Tab bit for the KeyMap's per-view mask. */
+enum {
+ TABBITS_STORAGE = 1u << 0,
+ TABBITS_SYSTEM = 1u << 1,
+ TABBITS_JOBS = 1u << 2,
+ TABBITS_PAGING = 1u << 3,
+ TABBITS_PS = 1u << 4,
+ TABBITS_FS = 1u << 5,
+ TABBITS_LOG = 1u << 6,
+ TABBITS_ALL = 0x7Fu,
+ TABBITS_ROWS = TABBITS_STORAGE | TABBITS_JOBS | TABBITS_PS | TABBITS_FS |
+ TABBITS_LOG,
};
-static const struct tui_hint storage_bar[] = {
- {"q", "quit"},
- {"TAB", "view"},
- {"s", "sort"},
- {"Enter", "details"},
+/* One table drives the footer hint and the ? overlay, so a key that moves
+ * cannot be documented in one place and forgotten in the other. */
+static const tui_binding keymap[] = {
+ /* views */
+ {"TAB", "next view", "views", TABBITS_ALL, true},
+ {"S-TAB", "previous view", "views", TABBITS_ALL, false},
+ {"1-7", "area, or view", "views", TABBITS_ALL, false},
+ {"click", "a tab", "views", TABBITS_ALL, false},
+ {"/", "filter", "views", TABBITS_STORAGE | TABBITS_JOBS, false},
+ {":", "command", "views", TABBITS_ALL, true},
+ /* moving */
+ {"j k", "one row", "moving", TABBITS_ROWS, false},
+ {"PgUp PgDn", "a page", "moving", TABBITS_ROWS, false},
+ {"g G", "first, last", "moving", TABBITS_ROWS, false},
+ {"wheel", "scroll", "moving", TABBITS_ROWS, false},
+ {"Enter", "details", "moving", TABBITS_STORAGE, false},
+ {"i", "inspector", "moving", TABBITS_STORAGE, false},
+ {"t", "fold TCBs", "moving", TABBITS_STORAGE, false},
+ {"s S", "sort, reverse", "moving", TABBITS_STORAGE | TABBITS_JOBS, true},
+ /* the screen */
+ {"q", "quit", "the screen", TABBITS_ALL, true},
+ {"p", "pause", "the screen", TABBITS_ALL, false},
+ {"r", "refresh now", "the screen", TABBITS_ALL, false},
+ {"+ -", "1..60 s", "the screen", TABBITS_ALL, false},
+ {"?", "help", "the screen", TABBITS_ALL, true},
};
+enum { KEYMAP_COUNT = (int)(sizeof keymap / sizeof keymap[0]) };
-static void draw_header(struct tui *t, const struct app *a) {
+/* Drawn and hit-tested from the same array, so a click lands on the tab it
+ * names. */
+static const char *const tab_labels[7] = {
+ "1 STORAGE", "2 SYSTEM", "3 JOBS", "4 PAGING", "5 PS", "6 FS", "7 LOG",
+};
+
+static void draw_header(tui *t, const app *a) {
char now[16];
char right[64];
- time_t clock_now = time(NULL);
+ char ident[96];
+ time_t clock_now = time(nullptr);
struct tm tm;
(void)localtime_r(&clock_now, &tm);
(void)strftime(now, sizeof now, "%H:%M:%S", &tm);
tui_fill(t, 0, 0, t->w, 1, ' ', TUI_BAR);
tui_printf(t, 1, 0, 7, TUI_KEYCAP, " ztop ");
- tui_printf(t, 7, 0, 8, TUI_META, " %s", ZTOP_VERSION);
- tui_printf(t, 15, 0, t->w - 40, TUI_PLAIN, " %s", a->host);
+ tui_printf(t, 7, 0, 8, TUI_META, "%s |", ZTOP_VERSION);
+ /* The identity stays on screen in every view: who you are looking at
+ * should not need a tab. */
+ if (a->have_sys)
+ (void)snprintf(ident, sizeof ident, "%s | %s | %s", a->sys.sysname,
+ a->sys.os, a->sys.machine);
+ else
+ (void)snprintf(ident, sizeof ident, "%s", a->host);
+ tui_printf(t, 14, 0, t->w - 40, TUI_PLAIN, "%s", ident);
if (a->collect_ms > 0)
(void)snprintf(right, sizeof right, "collect %dms %s", a->collect_ms,
now);
@@ -539,32 +842,115 @@ static void draw_header(struct tui *t, const struct app *a) {
" PAUSED ");
}
-static void draw_tabs(struct tui *t, const struct app *a) {
- static const char *const labels[4] = {"1 STORAGE", "2 SYSTEM", "3 JOBS",
- "4 PAGING"};
- int x = tui_tabs_draw(t, 0, 1, labels, 4, a->tab);
+static void draw_tabs(tui *t, const app *a) {
+ int x = tui_tabs_draw(t, 0, 1, tab_labels, 7, a->tab);
tui_printf(t, x + 1, 1, t->w - x - 2, TUI_META, "refresh %ds +/-",
a->interval);
}
-static void order_storage(struct app *a) {
- const struct vsm_info *v = &a->info[a->sub];
+/** @brief A line of text set into the panel's bottom border, like its
+ * title. */
+static void footer_line(tui *t, const char *text, tui_style st) {
+ tui_printf(t, 3, t->h - 2, t->w - 6, st, " %s ", text);
+}
- for (int i = 0; i < v->nsub; i++)
- a->sub_order[i] = i;
+/** @brief A dim label and its value, one blank apart. */
+static void kv(tui *t, int x, int y, int maxw, const char *label,
+ const char *value, tui_style st) {
+ int ll = (int)strlen(label);
+
+ if (ll >= maxw - 1)
+ return;
+ tui_printf(t, x, y, ll, TUI_META, "%s", label);
+ tui_printf(t, x + ll + 1, y, maxw - ll - 1, st, "%s", value);
+}
+
+/** @brief kv on one row, abandoned when it would cross @p limit; returns the
+ * column after it. */
+static int pair(tui *t, int x, int y, const char *label, const char *value,
+ tui_style st, int limit) {
+ int n = (int)strlen(label) + 1 + (int)strlen(value);
+
+ if (x + n > limit)
+ return x;
+ kv(t, x, y, n, label, value, st);
+ return x + n;
+}
+
+/* Case-folded substring match, so /csa finds CSAPOOL. */
+static bool match(const char *hay, const char *pat) {
+ size_t n = strlen(pat);
+
+ if (n == 0)
+ return true;
+ for (; *hay != '\0'; hay++) {
+ size_t i = 0;
+
+ while (i < n && hay[i] != '\0' &&
+ tolower((unsigned char)hay[i]) == tolower((unsigned char)pat[i]))
+ i++;
+ if (i == n)
+ return true;
+ }
+ return false;
+}
+
+/* The filter narrows the order array, so every reader of sub_order sees the
+ * filtered list and the sort applies to what is left. */
+static void order_storage(app *a) {
+ const vsm_info *v = &a->info[a->sub];
+ int n = 0;
+
+ for (int i = 0; i < v->nsub; i++) {
+ if (a->filter[0] != '\0') {
+ char key[24];
+
+ if (a->sub == 3)
+ (void)snprintf(key, sizeof key, "%u %08X", v->sub[i].id,
+ (unsigned int)v->sub[i].tcb);
+ else
+ (void)snprintf(key, sizeof key, "%u", v->sub[i].id);
+ if (!match(key, a->filter))
+ continue;
+ }
+ a->sub_order[n++] = i;
+ }
+ a->sub_rows = n;
sort_info = v;
sort_key = a->sub_sort;
sort_dir = a->sub_dir;
- qsort(a->sub_order, (size_t)v->nsub, sizeof a->sub_order[0], cmp_sub);
+ qsort(a->sub_order, (size_t)n, sizeof a->sub_order[0], cmp_sub);
+}
+
+/* Bodies live with the other detail drawing; the storage view places them
+ * either inside a popup or in the inspector pane. */
+static void subpool_box(tui *t, const app *a, tui_rect r, int idx);
+static void tcb_box(tui *t, const app *a, tui_rect r, int row);
+
+/* One place for the row layout: the views draw from this rect and the
+ * mouse hit-tests against the same one, so a header change cannot leave a
+ * click target behind. STORAGE keeps its area tabs on the row above. */
+static tui_rect table_rect(int w, int h, int tab) {
+ int y = tab == 0 ? 5 : 3;
+
+ return (tui_rect){1, y, w - 2, h - y - 2};
}
-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};
+static int table_rows(int w, int h, int tab) {
+ int n = table_rect(w, h, tab).h - 1;
+
+ return n > 0 ? n : 1;
+}
+
+static void draw_storage(tui *t, app *a) {
+ const vsm_info *v = &a->info[a->sub];
+ tui_rect r = table_rect(t->w, t->h, 0);
+ tui_rect pane = {0, 0, 0, 0};
+ bool side = a->inspector && t->w >= 110;
char used[16], freed[16], mapped[16], total[16], pcbuf[8];
char head[24];
- struct tui_col cols[8];
+ tui_col cols[8];
static const int col_of[SS_COUNT] = {0, 1, 2, 3, 4, 6};
int p = pct(v);
@@ -574,10 +960,16 @@ static void draw_storage(struct tui *t, struct app *a) {
a->sub_dir < 0 ? "^" : "v");
cols[col_of[a->sub_sort]].title = head;
a->storage.cols = cols;
- tui_printf(t, 1, 3, 6, a->sub == 0 ? TUI_TAB_ON : TUI_TAB_OFF, " CSA ");
- tui_printf(t, 7, 3, 6, a->sub == 1 ? TUI_TAB_ON : TUI_TAB_OFF, " SQA ");
- tui_printf(t, 13, 3, 7, a->sub == 2 ? TUI_TAB_ON : TUI_TAB_OFF, " LSQA ");
- tui_printf(t, 20, 3, 6, a->sub == 3 ? TUI_TAB_ON : TUI_TAB_OFF, " PVT ");
+ tui_printf(t, 1, r.y - 2, 6, a->sub == 0 ? TUI_TAB_ON : TUI_TAB_OFF,
+ " CSA ");
+ tui_printf(t, 7, r.y - 2, 6, a->sub == 1 ? TUI_TAB_ON : TUI_TAB_OFF,
+ " SQA ");
+ tui_printf(t, 13, r.y - 2, 7, a->sub == 2 ? TUI_TAB_ON : TUI_TAB_OFF,
+ " LSQA ");
+ tui_printf(t, 20, r.y - 2, 6, a->sub == 3 ? TUI_TAB_ON : TUI_TAB_OFF,
+ " PVT ");
+ if (side)
+ tui_split_h(r, r.w - 46, &r, &pane);
if (!a->have[a->sub]) {
tui_printf(t, 1, 6, t->w - 2, TUI_BAD, "%s: %s", area_upper[a->sub],
@@ -594,54 +986,71 @@ static void draw_storage(struct tui *t, struct app *a) {
(void)snprintf(total, sizeof total, "-");
(void)snprintf(pcbuf, sizeof pcbuf, "use -");
}
- tui_printf(t, 1, 4, t->w - 16, TUI_PLAIN,
- "used %s free %s mapped %s total %s", used, freed, mapped,
- total);
- tui_printf(t, t->w - 15 - (int)strlen(pcbuf), 4, (int)strlen(pcbuf),
+ {
+ int gx = t->w - 20 - (int)strlen(pcbuf);
+ int x = 2;
+
+ x = pair(t, x, 4, "used", used, TUI_ACCENT, gx);
+ x = pair(t, x + 2, 4, "free", freed, TUI_PLAIN, gx);
+ x = pair(t, x + 2, 4, "mapped", mapped, TUI_PLAIN, gx);
+ (void)pair(t, x + 2, 4, "total", total, TUI_PLAIN, gx);
+ }
+ tui_printf(t, t->w - 19 - (int)strlen(pcbuf), 4, (int)strlen(pcbuf),
p < 0 ? TUI_META
: p < 70 ? TUI_GOOD
: p < 85 ? TUI_WARN
: TUI_BAD,
"%s", pcbuf);
if (p >= 0)
- tui_progress(t, t->w - 14, 4, 12, p);
- tui_table_draw(t, r, &a->storage, v->nsub, storage_cell, NULL, a);
+ tui_progress(t, t->w - 18, 4, 16, p);
+ if (folded(a)) {
+ a->storage.cols = pvt_fold_cols;
+ a->storage.vp = a->pvt_vp;
+ tui_table_draw(t, r, &a->storage, a->npvt, pvt_cell, nullptr, a);
+ } else {
+ tui_table_draw(t, r, &a->storage, a->sub_rows, storage_cell, nullptr,
+ a);
+ }
+ if (side) {
+ if (folded(a) && a->pvt_vp.sel < a->npvt)
+ tcb_box(t, a, pane, a->pvt_vp.sel);
+ else if (!folded(a) && a->sub_rows > 0)
+ subpool_box(t, a, pane, a->sub_order[a->storage.vp.sel]);
+ }
- 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) {
- char ua[16], ul[16];
+ if (a->err[a->sub][0] != '\0') {
+ footer_line(t, a->err[a->sub], TUI_BAD);
+ } else if (v->unalloc_valid) {
+ char ua[16], ul[16], note[96];
human(v->unalloc, ua, sizeof ua);
human(v->largest_unalloc, ul, sizeof ul);
- tui_printf(t, 1, t->h - 2, t->w - 2, TUI_META,
- "unallocated %s in %u blocks, largest %s", ua,
- v->unalloc_blocks, ul);
+ (void)snprintf(note, sizeof note,
+ "unallocated %s in %u blocks, largest %s", ua,
+ v->unalloc_blocks, ul);
+ footer_line(t, note, TUI_META);
}
-}
+ if (a->ntrend[a->sub] > 0 && t->w >= 100) {
+ int n = a->ntrend[a->sub];
+ int x = t->w - 4 - n;
-/** @brief A dim label and its value, one blank apart. */
-static void kv(struct tui *t, int x, int y, int maxw, const char *label,
- const char *value, tui_style st) {
- int ll = (int)strlen(label);
-
- if (ll >= maxw - 1)
- return;
- tui_printf(t, x, y, ll, TUI_META, "%s", label);
- tui_printf(t, x + ll + 1, y, maxw - ll - 1, st, "%s", value);
+ tui_printf(t, x - 5, t->h - 2, 4, TUI_META, "used");
+ tui_sparkline(t, x, t->h - 2, a->trend[a->sub], n, TUI_ACCENT);
+ }
}
-/** @brief An accent heading with a dim rule filling the row. */
-static void section(struct tui *t, int y, const char *name) {
+/** @brief An accent heading with a dim rule filling the row, stopped at the
+ * panel border. */
+static void section(tui *t, int y, const char *name) {
int n = (int)strlen(name);
tui_printf(t, 1, y, n, TUI_ACCENT, "%s", name);
- if (n + 2 < t->w)
- tui_fill(t, n + 2, y, t->w - n - 2, 1, '-', TUI_META);
+ if (n + 2 < t->w - 1)
+ tui_fill(t, n + 2, y, t->w - n - 3, 1, '-', TUI_META);
}
-static void draw_system(struct tui *t, const struct app *a) {
- const struct zsys *z = &a->sys;
+static void draw_system(tui *t, const app *a) {
+ const zsys *z = &a->sys;
char b1[32], b2[32];
int half = t->w / 2;
@@ -681,8 +1090,8 @@ static void draw_system(struct tui *t, const struct app *a) {
}
}
-static void draw_paging(struct tui *t, const struct app *a) {
- const struct zpage *p = &a->page;
+static void draw_paging(tui *t, const app *a) {
+ const zpage *p = &a->page;
char b[48];
int half = t->w / 2;
@@ -721,19 +1130,27 @@ static void draw_paging(struct tui *t, const struct app *a) {
kv(t, half, 12, t->w - half - 1, "control intervals", b, TUI_PLAIN);
}
-static void draw_jobs(struct tui *t, struct app *a) {
- tui_rect r = {0, 3, t->w, t->h - 5};
+static void draw_jobs(tui *t, app *a) {
+ tui_rect r = table_rect(t->w, t->h, 2);
char head[24];
- struct tui_col cols[3];
+ tui_col cols[3];
if (a->have_sys) {
- for (int i = 0; i < a->sys.njobs; i++)
- a->job_order[i] = i;
+ int n = 0;
+
+ for (int i = 0; i < a->sys.njobs; i++) {
+ char key[24];
+
+ (void)snprintf(key, sizeof key, "%u %s", a->sys.job[i].asid,
+ a->sys.job[i].name);
+ if (match(key, a->filter))
+ a->job_order[n++] = i;
+ }
+ a->job_rows = n;
sort_sys = &a->sys;
sort_key = a->job_sort;
sort_dir = a->job_dir;
- qsort(a->job_order, (size_t)a->sys.njobs, sizeof a->job_order[0],
- cmp_job);
+ qsort(a->job_order, (size_t)n, sizeof a->job_order[0], cmp_job);
(void)memcpy(cols, job_cols, sizeof cols);
(void)snprintf(head, sizeof head, "%s %s", job_sort_names[a->job_sort],
a->job_dir < 0 ? "^" : "v");
@@ -744,93 +1161,461 @@ static void draw_jobs(struct tui *t, struct app *a) {
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);
+ tui_table_draw(t, r, &a->jobs, a->job_rows, job_cell, nullptr, a);
+ {
+ char note[64];
+
+ (void)snprintf(note, sizeof note, "%d address spaces, %u slots",
+ a->sys.njobs, a->sys.slots);
+ footer_line(t, note, TUI_LABEL);
+ }
}
/** @brief Everything about the selected subpool, over the table. */
-static void draw_subpool(struct tui *t, const struct app *a) {
- const struct vsm_info *v = &a->info[a->sub];
- int i = v->nsub ? a->sub_order[a->storage.vp.sel] : 0;
- const struct vsm_subpool *s = &v->sub[i];
- int w = 46;
- int h = 12;
- int x = (t->w - w) / 2;
- int y = (t->h - h) / 2;
- char u[16], f[16], m[16], l[16], b[32];
+/* One subpool, painted into whatever rectangle is handed in: the popup and
+ * the inspector pane share this body. */
+static void subpool_box(tui *t, const app *a, tui_rect r, int idx) {
+ const vsm_info *v = &a->info[a->sub];
+ const vsm_subpool *s = &v->sub[idx];
+ char key[16], blocks[16], used[16], freed[16], mapped[16], largest[16];
+ char below[16], above[16], where[32], title[32];
+ const char *k[9];
+ const char *val[9];
+ int n = 0;
- if (x < 0)
- x = 0;
- if (y < 0)
- y = 0;
- human(s->used, u, sizeof u);
- human(s->free, f, sizeof f);
- human(s->foot, m, sizeof m);
- human(s->largest, l, sizeof l);
- tui_fill(t, x, y, w, h, ' ', TUI_PLAIN);
- (void)snprintf(b, sizeof b, "subpool %u", s->id);
- tui_box_frame(t, x, y, w, h, TUI_ACCENT, b, TUI_ACCENT);
- (void)snprintf(b, sizeof b, "%u", s->key);
- kv(t, x + 2, y + 2, w - 4, "key", b, TUI_PLAIN);
- (void)snprintf(b, sizeof b, "%u", s->blocks);
- kv(t, x + 2, y + 3, w - 4, "blocks", b, TUI_PLAIN);
- kv(t, x + 2, y + 4, w - 4, "used", u, TUI_PLAIN);
- kv(t, x + 2, y + 5, w - 4, "free", f, TUI_PLAIN);
- kv(t, x + 2, y + 6, w - 4, "mapped", m, TUI_PLAIN);
- kv(t, x + 2, y + 7, w - 4, "largest", l, TUI_PLAIN);
- if (v->area == VSM_PVT) {
- (void)snprintf(b, sizeof b, "%08X", (unsigned int)s->tcb);
- kv(t, x + 2, y + 8, w - 4, "tcb", b, TUI_PLAIN);
- } else {
- (void)snprintf(b, sizeof b, "%08X-%08X", (unsigned int)s->lo,
+ human(s->used, used, sizeof used);
+ human(s->free, freed, sizeof freed);
+ human(s->foot, mapped, sizeof mapped);
+ human(s->largest, largest, sizeof largest);
+ human(s->below, below, sizeof below);
+ human(s->above, above, sizeof above);
+ (void)snprintf(key, sizeof key, "%u", s->key);
+ (void)snprintf(blocks, sizeof blocks, "%u", s->blocks);
+ if (v->area == VSM_PVT)
+ (void)snprintf(where, sizeof where, "%08X", (unsigned int)s->tcb);
+ else
+ (void)snprintf(where, sizeof where, "%08X-%08X", (unsigned int)s->lo,
(unsigned int)s->hi);
- kv(t, x + 2, y + 8, w - 4, "address", b, TUI_PLAIN);
+ k[n] = "key", val[n++] = key;
+ k[n] = "blocks", val[n++] = blocks;
+ k[n] = "used", val[n++] = used;
+ k[n] = "below 16M", val[n++] = below;
+ k[n] = "above 16M", val[n++] = above;
+ k[n] = "free", val[n++] = freed;
+ k[n] = "mapped", val[n++] = mapped;
+ k[n] = "largest", val[n++] = largest;
+ k[n] = v->area == VSM_PVT ? "tcb" : "address", val[n++] = where;
+
+ (void)snprintf(title, sizeof title, "subpool %u", s->id);
+ tui_fill(t, r.x, r.y, r.w, r.h, ' ', TUI_PLAIN);
+ tui_box_frame(t, r.x, r.y, r.w, r.h, TUI_FRAME, title, TUI_ACCENT);
+ for (int i = 0; i < n && r.y + 2 + i < r.y + r.h - 1; i++)
+ kv(t, r.x + 2, r.y + 2 + i, r.w - 4, k[i], val[i], TUI_PLAIN);
+ if (r.h >= 4)
+ tui_printf(t, r.x + 2, r.y + r.h - 2, r.w - 4, TUI_META,
+ "any key closes");
+}
+
+/* One folded TCB row: its totals, then the subpools that make them up. */
+static void tcb_box(tui *t, const app *a, tui_rect r, int row) {
+ const vsm_info *v = &a->info[3];
+ const pvt_row *p = &a->pvt[row];
+ char used[16], below[16], above[16], subs[16], title[40];
+ int line;
+
+ human(p->used, used, sizeof used);
+ human(p->below, below, sizeof below);
+ human(p->above, above, sizeof above);
+ (void)snprintf(subs, sizeof subs, "%u", p->nsub);
+ (void)snprintf(title, sizeof title, "TCB %08X", (unsigned int)p->tcb);
+ tui_fill(t, r.x, r.y, r.w, r.h, ' ', TUI_PLAIN);
+ tui_box_frame(t, r.x, r.y, r.w, r.h, TUI_FRAME, title, TUI_ACCENT);
+ kv(t, r.x + 2, r.y + 2, r.w - 4, "subpools", subs, TUI_PLAIN);
+ kv(t, r.x + 2, r.y + 3, r.w - 4, "used", used, TUI_PLAIN);
+ kv(t, r.x + 2, r.y + 4, r.w - 4, "below 16M", below, TUI_PLAIN);
+ kv(t, r.x + 2, r.y + 5, r.w - 4, "above 16M", above, TUI_PLAIN);
+ line = r.y + 7;
+ if (line < r.y + r.h - 1)
+ tui_printf(t, r.x + 2, line++, r.w - 4, TUI_LABEL, "subpools");
+ for (int i = 0; i < v->nsub && line < r.y + r.h - 1; i++) {
+ const vsm_subpool *s = &v->sub[i];
+ char u[16], b[16], ab[16];
+
+ if (s->tcb != p->tcb)
+ continue;
+ human(s->used, u, sizeof u);
+ human(s->below, b, sizeof b);
+ human(s->above, ab, sizeof ab);
+ tui_printf(t, r.x + 2, line++, r.w - 4, TUI_PLAIN, "%2u %8s %s%s",
+ s->id, u, b[0] == '0' ? "" : "<16M ",
+ ab[0] == '0' ? "" : ">16M");
}
- tui_printf(t, x + 2, y + h - 2, w - 4, TUI_META, "any key closes");
+ if (r.h >= 4)
+ tui_printf(t, r.x + 2, r.y + r.h - 2, r.w - 4, TUI_META,
+ "any key closes");
}
-static void draw_help(struct tui *t) {
- static const struct tui_hint views[] = {
- {"TAB", "next view"},
- {"Shift-TAB", "previous view"},
- {"1-4", "CSA SQA LSQA PVT"},
- {"click", "a tab"},
- };
- static const struct tui_hint moving[] = {
- {"j k", "one row"}, {"PgUp PgDn", "a page"}, {"g G", "first, last"},
- {"wheel", "scroll"}, {"Enter", "details"}, {"s S", "sort, reverse"},
- };
- static const struct tui_hint screen[] = {
- {"p", "pause"}, {"r", "refresh now"}, {"+ -", "interval 1..60 s"},
- {"?", "help"}, {"q", "quit"},
- };
- int w = t->w < 64 ? t->w - 2 : 62;
- int h = 15;
- int x = (t->w - w) / 2;
- int y = (t->h - h) / 2;
+static void draw_popup(tui *t, app *a) {
+ tui_rect r = {(t->w - 46) / 2, (t->h - 13) / 2, 46, 13};
+ const vsm_info *v = &a->info[a->sub];
+
+ if (r.x < 0)
+ r.x = 0;
+ if (r.y < 0)
+ r.y = 0;
+ if (a->tcb_popup) {
+ if (a->pvt_vp.sel < a->npvt)
+ tcb_box(t, a, r, a->pvt_vp.sel);
+ } else if (v->nsub > 0) {
+ subpool_box(t, a, r, a->sub_order[a->storage.vp.sel]);
+ }
+}
- if (x < 0)
- x = 0;
- if (y < 0)
- y = 0;
- tui_fill(t, x, y, w, h, ' ', TUI_PLAIN);
- tui_box_frame(t, x, y, w, h, TUI_ACCENT, "keys", TUI_ACCENT);
- tui_printf(t, x + 2, y + 2, w - 4, TUI_LABEL, "views");
- tui_hints(t, x + 2, y + 3, w - 4, views, 4);
- tui_printf(t, x + 2, y + 5, w - 4, TUI_LABEL, "moving");
- tui_hints(t, x + 2, y + 6, w - 4, moving, 3);
- tui_hints(t, x + 2, y + 7, w - 4, moving + 3, 3);
- tui_printf(t, x + 2, y + 9, w - 4, TUI_LABEL, "the screen");
- tui_hints(t, x + 2, y + 10, w - 4, screen, 5);
+static void draw_help(tui *t) {
+ tui_keymap_help(t, keymap, KEYMAP_COUNT, "keys");
+}
+
+/* A filter edit re-runs the orders, because every reader indexes through
+ * them: the table, the detail line, the popup and the mouse. */
+static void filter_changed(app *a) {
+ (void)snprintf(a->filter, sizeof a->filter, "%s", a->fin.buf);
+ order_storage(a);
+ build_pvt(a);
+ a->storage.vp.sel = 0;
+ a->storage.vp.top = 0;
+ a->pvt_vp.sel = 0;
+ a->pvt_vp.top = 0;
+ a->jobs.vp.sel = 0;
+ a->jobs.vp.top = 0;
+}
+
+static void run_command(app *a, const char *cmd) {
+ char c[32];
+ char *p = c;
+ size_t n;
+
+ (void)snprintf(c, sizeof c, "%s", cmd);
+ for (char *q = c; *q != '\0'; q++)
+ *q = (char)tolower((unsigned char)*q);
+ while (*p == ' ')
+ p++;
+ n = strlen(p);
+ while (n > 0 && p[n - 1] == ' ')
+ p[--n] = '\0';
+
+ if (strcmp(p, "csa") == 0 || strcmp(p, "sqa") == 0 ||
+ strcmp(p, "lsqa") == 0 || strcmp(p, "pvt") == 0) {
+ a->tab = 0;
+ if (p[0] == 'c')
+ a->sub = 0;
+ else if (p[0] == 'l')
+ a->sub = 2;
+ else if (p[0] == 'p')
+ a->sub = 3;
+ else
+ a->sub = 1;
+ } else if (strcmp(p, "sys") == 0) {
+ a->tab = 1;
+ } else if (strcmp(p, "jobs") == 0 || strcmp(p, "da") == 0) {
+ a->tab = 2;
+ } else if (strcmp(p, "page") == 0) {
+ a->tab = 3;
+ } else if (strcmp(p, "ps") == 0) {
+ a->tab = 4;
+ a->have_ps = uss_ps_read(&a->ps);
+ } else if (strcmp(p, "fs") == 0) {
+ a->tab = 5;
+ a->have_fs = uss_fs_read(&a->fs);
+ } else if (strcmp(p, "fold") == 0) {
+ a->tab = 0;
+ a->sub = 3;
+ a->pvt_fold = !a->pvt_fold;
+ } else if (strcmp(p, "log") == 0) {
+ a->tab = 6;
+ if (!a->log_on)
+ log_start(a);
+ log_poll(a);
+ } else if (strcmp(p, "pause") == 0) {
+ a->paused = !a->paused;
+ } else if (strcmp(p, "help") == 0) {
+ a->help = true;
+ } else if (strcmp(p, "quit") == 0 || strcmp(p, "q") == 0) {
+ a->tapp->quit = true;
+ }
+}
+
+static const tui_col ps_cols[] = {
+ {"PID", 9, true}, {"PPID", 9, true}, {"UID", 7, true},
+ {"ST", 3, false}, {"CPU", 9, true}, {"COMMAND", 44, false},
+};
+
+static const tui_col fs_cols[] = {
+ {"MOUNT", 28, false}, {"TYPE", 9, false}, {"SIZE", 9, true},
+ {"FREE", 9, true}, {"USED", 5, true}, {"RO", 2, false},
+ {"FS", 45, false},
+};
+
+static void ps_cell(void *ctx, int row, int col, char *buf, size_t len) {
+ const app *a = ctx;
+ const uss_proc *p;
+
+ if (row >= a->ps.nproc) {
+ buf[0] = '\0';
+ return;
+ }
+ p = &a->ps.proc[row];
+ switch (col) {
+ case 0:
+ (void)snprintf(buf, len, "%d", p->pid);
+ break;
+ case 1:
+ (void)snprintf(buf, len, "%d", p->ppid);
+ break;
+ case 2:
+ (void)snprintf(buf, len, "%d", p->uid);
+ break;
+ case 3:
+ (void)snprintf(buf, len, "%c%s", p->st, p->swapped ? "S" : "");
+ break;
+ case 4:
+ (void)snprintf(buf, len, "%lu.%02lu", p->cpu_ms / 1000,
+ (p->cpu_ms % 1000) / 10);
+ break;
+ default:
+ (void)snprintf(buf, len, "%s", p->cmd);
+ break;
+ }
+}
+
+static void fs_cell(void *ctx, int row, int col, char *buf, size_t len) {
+ const app *a = ctx;
+ const uss_fs *f;
+ char b[16];
+
+ if (row >= a->fs.nfs) {
+ buf[0] = '\0';
+ return;
+ }
+ f = &a->fs.fs[row];
+ switch (col) {
+ case 0:
+ (void)snprintf(buf, len, "%s", f->mount);
+ break;
+ case 1:
+ (void)snprintf(buf, len, "%s", f->type);
+ break;
+ case 2:
+ human(f->kb_total * 1024, b, sizeof b);
+ (void)snprintf(buf, len, "%s", f->ok ? b : "-");
+ break;
+ case 3:
+ human(f->kb_free * 1024, b, sizeof b);
+ (void)snprintf(buf, len, "%s", f->ok ? b : "-");
+ break;
+ case 4:
+ if (f->pct < 0)
+ (void)snprintf(buf, len, "-");
+ else
+ (void)snprintf(buf, len, "%d%%", f->pct);
+ break;
+ case 5:
+ (void)snprintf(buf, len, "%s", f->rdonly ? "ro" : "rw");
+ break;
+ default:
+ (void)snprintf(buf, len, "%s", f->fsname);
+ break;
+ }
+}
+
+static void draw_ps(tui *t, app *a) {
+ tui_rect r = table_rect(t->w, t->h, 4);
+ char note[64];
+
+ if (!a->have_ps) {
+ tui_printf(t, 1, 4, t->w - 2, TUI_BAD, "%s", a->ps.err);
+ return;
+ }
+ tui_table_draw(t, r, &a->pst, a->ps.nproc, ps_cell, nullptr, a);
+ (void)snprintf(note, sizeof note, "%d processes%s", a->ps.nproc,
+ a->ps.truncated ? ", more not shown" : "");
+ footer_line(t, note, TUI_LABEL);
+}
+
+static void draw_fs(tui *t, app *a) {
+ tui_rect r = table_rect(t->w, t->h, 5);
+ char note[96];
+
+ if (!a->have_fs) {
+ tui_printf(t, 1, 4, t->w - 2, TUI_BAD, "%s", a->fs.err);
+ return;
+ }
+ tui_table_draw(t, r, &a->fst, a->fs.nfs, fs_cell, nullptr, a);
+ (void)snprintf(note, sizeof note, "%d file systems%s", a->fs.nfs,
+ a->fs.truncated ? ", more not shown" : "");
+ footer_line(t, note, TUI_LABEL);
+}
+
+/* ---- the console log ---- */
+
+/* One line of the ring. A line that arrives when the ring is full
+ * overwrites the oldest, which is what a console does. */
+static void log_put(app *a, const char *line, int len) {
+ char *dst = a->log[a->log_next];
+
+ if (len > LOG_COLS - 1)
+ len = LOG_COLS - 1;
+ if (len < 0)
+ len = 0;
+ (void)memcpy(dst, line, (size_t)len);
+ dst[len] = '\0';
+ a->log_next = (a->log_next + 1) % LOG_LINES;
+ if (a->nlog < LOG_LINES)
+ a->nlog++;
+}
+
+/* Line i, counted from the oldest kept. */
+static const char *log_at(const app *a, int i) {
+ return a->log[(a->log_next + LOG_LINES - a->nlog + i) % LOG_LINES];
+}
+
+/* The object walk lives in src/mdb.c: it parses bytes from another
+ * address space and has a test of its own. */
+static void log_mdb(app *a) {
+ char job[16];
+ char text[MDB_TEXT_MAX];
+ char line[LOG_COLS];
+ int n;
+
+ if (!mdb_line(a->mdb, a->mdb_len, job, sizeof job, text, sizeof text))
+ return;
+ n = snprintf(line, sizeof line, "%-8s %s", job, text);
+ if (n < 0)
+ return;
+ if (n > (int)sizeof line - 1)
+ n = (int)sizeof line - 1;
+ log_put(a, line, n);
+}
+
+/* Take the console down. Called on quit, and safe to call when it was
+ * never up. */
+static void log_stop(app *a) {
+ if (!a->log_on)
+ return;
+ a->creq.op = ZMCS_DEACTIVATE;
+ a->creq.consid = &a->creq_consid;
+ (void)zmcs(&a->creq);
+ a->log_on = false;
+}
+
+/* Open the console. A refusal is not fatal: the other views do not need
+ * it, so the reason is kept and shown on the tab. */
+/* The console stub keeps the MCSOPER control blocks in its own CSECT,
+ * which is read-only in this link: it has to be built as a 31-bit module
+ * and thunked to (src/zmcs.s says why). Until that module exists, -c
+ * reports it instead of taking a 0C4 on the first privileged call. */
+static bool console_built(void) {
+ return false;
+}
+
+static void log_start(app *a) {
+ if (!console_opt) {
+ (void)snprintf(a->log_err, sizeof a->log_err,
+ "console off: ztop -c after make auth");
+ return;
+ }
+ if (!console_built()) {
+ (void)snprintf(a->log_err, sizeof a->log_err,
+ "console: the stub is not a 31-bit module yet");
+ return;
+ }
+ a->creq = (zmcs_req){};
+ console_name(a->creq_name);
+ a->creq.op = ZMCS_ACTIVATE;
+ a->creq.name = a->creq_name;
+ a->creq.consid = &a->creq_consid;
+ (void)zmcs(&a->creq);
+ if (a->creq.rc > 4) {
+ if (a->creq.rc == 12)
+ (void)snprintf(a->log_err, sizeof a->log_err,
+ "console needs APF authorization: MODESET rc %d",
+ a->creq.rc);
+ else
+ (void)snprintf(a->log_err, sizeof a->log_err,
+ "MCSOPER activate: rc %d rsn %d", a->creq.rc,
+ a->creq.rsn);
+ return;
+ }
+ a->log_on = true;
+ a->log_err[0] = '\0';
+}
+
+/* Drain what is queued. Bounded: a console burst must not stall a frame,
+ * and one call per tick is the steady state, which costs a single
+ * MCSOPMSG. */
+static void log_poll(app *a) {
+ int i;
+
+ if (!a->log_on)
+ return;
+ /* QLIMIT bounds the queue at the console end; this bounds the work per
+ * refresh, so a burst cannot stall a redraw. */
+ a->creq.consid = &a->creq_consid;
+ a->creq.buf = a->mdb;
+ a->creq.len = &a->mdb_len;
+ for (i = 0; i < 200; i++) {
+ a->mdb_len = (int)sizeof a->mdb;
+ a->creq.op = ZMCS_GETMSG;
+ (void)zmcs(&a->creq);
+ if (a->creq.rc == 8) /* nothing queued */
+ return;
+ if (a->creq.rc != 0 && a->creq.rc != 4) {
+ (void)snprintf(a->log_err, sizeof a->log_err,
+ "MCSOPMSG: rc %d rsn %d", a->creq.rc, a->creq.rsn);
+ log_stop(a);
+ return;
+ }
+ log_mdb(a);
+ }
+}
+
+static void draw_log(tui *t, app *a) {
+ tui_rect r = table_rect(t->w, t->h, 6);
+ int rows = table_rows(t->w, t->h, 6);
+ char note[64];
+
+ if (!a->log_on) {
+ tui_printf(t, 1, 4, t->w - 2, TUI_BAD, "%s",
+ a->log_err[0] != '\0' ? a->log_err
+ : "the console is not open");
+ return;
+ }
+ tui_viewport_clamp(&a->log_vp, a->nlog, rows - 1);
+ for (int i = 0; i < rows - 1 && a->log_vp.top + i < a->nlog; i++) {
+ int line = a->log_vp.top + i;
+
+ tui_printf(t, r.x, r.y + 1 + i, r.w,
+ line == a->log_vp.sel ? TUI_TAB_ON : TUI_PLAIN, "%s",
+ log_at(a, line));
+ }
+ (void)snprintf(note, sizeof note, "%d messages%s", a->nlog,
+ a->nlog >= LOG_LINES ? ", oldest dropped" : "");
+ footer_line(t, note, TUI_LABEL);
}
/** @brief The right half of the status line: what is under the cursor. */
-static void detail(struct app *a, char *buf, size_t len) {
+static void detail(app *a, char *buf, size_t len) {
if (a->paused) {
(void)snprintf(buf, len, "PAUSED");
- } else if (a->tab == 0 && a->have[a->sub] && a->info[a->sub].nsub > 0) {
- const struct vsm_subpool *sp = &a->info[a->sub].sub[a->storage.vp.sel];
+ } else if (folded(a) && a->pvt_vp.sel < a->npvt) {
+ const pvt_row *p = &a->pvt[a->pvt_vp.sel];
+ char u[16];
+
+ human(p->used, u, sizeof u);
+ (void)snprintf(buf, len, "TCB %08X %u subpools %s",
+ (unsigned int)p->tcb, p->nsub, u);
+ } else if (a->tab == 0 && a->have[a->sub] && a->sub_rows > 0) {
+ const vsm_info *v = &a->info[a->sub];
+ const vsm_subpool *sp = &v->sub[a->sub_order[vp_of(a)->sel]];
if (a->sub == 3)
(void)snprintf(buf, len, "sp %u tcb %08X", sp->id,
@@ -840,43 +1625,86 @@ static void detail(struct app *a, char *buf, size_t len) {
else
(void)snprintf(buf, len, "sp %u %08X-%08X", sp->id,
(unsigned int)sp->lo, (unsigned int)sp->hi);
- } else if (a->tab == 2 && a->have_sys && a->sys.njobs > 0) {
- const struct zjob *j = &a->sys.job[a->jobs.vp.sel];
+ } else if (a->tab == 2 && a->have_sys && a->job_rows > 0) {
+ const zjob *j = &a->sys.job[a->job_order[a->jobs.vp.sel]];
(void)snprintf(buf, len, "asid %u %s", j->asid, j->name);
+ } else if (a->tab == 4 && a->have_ps && a->ps.nproc > 0) {
+ const uss_proc *p = &a->ps.proc[a->pst.vp.sel];
+
+ (void)snprintf(buf, len, "pid %d uid %d %s", p->pid, p->uid, p->cmd);
+ } else if (a->tab == 5 && a->have_fs && a->fs.nfs > 0) {
+ const uss_fs *f = &a->fs.fs[a->fst.vp.sel];
+
+ if (f->ok)
+ (void)snprintf(buf, len, "%s %llu%% used", f->mount,
+ (unsigned long long)(f->pct < 0 ? 0 : f->pct));
+ else
+ (void)snprintf(buf, len, "%s statvfs errno %d", f->mount, f->eno);
} else {
buf[0] = '\0';
}
}
-static void view(void *model, struct tui *t) {
- struct app *a = model;
+static void view(void *model, tui *t) {
+ static const char *const title[7] = {
+ "STORAGE", "SYSTEM", "JOBS", "PAGING",
+ "PROCESSES", "FILE SYSTEMS", "CONSOLE",
+ };
+ app *a = model;
char right[48];
tui_clear(t);
draw_header(t, a);
draw_tabs(t, a);
- tui_fill(t, 0, 2, t->w, 1, '-', TUI_STYLE(7, 0, TUI_DIM));
+ /* The tables draw a clamped copy, so the model's selection is brought
+ * into range here, before the detail lines read it. */
+ tui_viewport_clamp(&a->storage.vp, a->info[a->sub].nsub,
+ table_rows(t->w, t->h, 0));
+ tui_viewport_clamp(&a->jobs.vp, a->sys.njobs, table_rows(t->w, t->h, 2));
+ tui_viewport_clamp(&a->pst.vp, a->ps.nproc, table_rows(t->w, t->h, 4));
+ tui_viewport_clamp(&a->fst.vp, a->fs.nfs, table_rows(t->w, t->h, 5));
+ tui_viewport_clamp(&a->log_vp, a->nlog, table_rows(t->w, t->h, 6));
+ tui_viewport_clamp(&a->pvt_vp, a->npvt, table_rows(t->w, t->h, 0));
+ if (t->w >= 70 && t->h >= 16)
+ tui_box_frame(t, 0, 2, t->w, t->h - 3, TUI_FRAME, title[a->tab],
+ TUI_ACCENT);
- if (t->w < 70 || t->h < 14) {
- tui_printf(t, 1, 3, 0, TUI_BAD, "terminal too small: need 70x14");
+ if (t->w < 70 || t->h < 16) {
+ tui_printf(t, 1, 3, 0, TUI_BAD, "terminal too small: need 70x16");
} else if (a->tab == 0) {
draw_storage(t, a);
} else if (a->tab == 1) {
draw_system(t, a);
} else if (a->tab == 2) {
draw_jobs(t, a);
+ } else if (a->tab == 4) {
+ draw_ps(t, a);
+ } else if (a->tab == 5) {
+ draw_fs(t, a);
+ } else if (a->tab == 6) {
+ draw_log(t, a);
} else {
draw_paging(t, a);
}
if (a->popup)
- draw_subpool(t, a);
+ draw_popup(t, a);
if (a->help)
draw_help(t);
detail(a, right, sizeof right);
- tui_statusbar(t, NULL, right);
- tui_hints(t, 0, t->h - 1, t->w - 20, a->tab == 0 ? storage_bar : view_bar,
- 4);
+ tui_statusbar(t, nullptr, right);
+ if (a->filtering) {
+ tui_put(t, 0, t->h - 1, "/", 1, TUI_KEYCAP);
+ tui_input_draw(t, (tui_rect){1, t->h - 1, t->w - 1, 1}, &a->fin,
+ TUI_BAR);
+ } else if (a->commanding) {
+ tui_put(t, 0, t->h - 1, ":", 1, TUI_KEYCAP);
+ tui_input_draw(t, (tui_rect){1, t->h - 1, t->w - 1, 1}, &a->cin,
+ TUI_BAR);
+ } else {
+ tui_keymap_footer(t, 0, t->h - 1, t->w - 20, keymap, KEYMAP_COUNT,
+ a->tab);
+ }
}
static bool parse_areas(const char *s, unsigned int *mask) {
@@ -916,71 +1744,63 @@ static void usage(FILE *f) {
" -p auxiliary storage: page data sets, local paging, VIO journal\n"
" -x dump the VSMLIST work and data areas (one-shot only)\n"
" -d force the interactive view (the default on a terminal)\n"
+ " -c open the MCS console for the LOG view (needs APF, see\n"
+ " make auth; an unauthorized program ends with S047)\n"
" -h this text\n");
}
-static void wheel(struct app *a, int dir, int height) {
- if (a->tab == 0)
- tui_viewport_move(&a->storage.vp, dir, a->info[a->sub].nsub, height);
- else if (a->tab == 2)
- tui_viewport_move(&a->jobs.vp, dir, a->sys.njobs, height);
+static void wheel(app *a, int dir, int height) {
+ if (a->tab == 0 || a->tab == 2 || a->tab == 6)
+ tui_viewport_move(vp_of(a), dir, vrows(a), height);
}
/** @brief Tabs, sub-tabs, table rows and the wheel. */
-static bool mouse_event(struct tui_app *app, const struct tui_msg *m) {
- static const char *const views[3] = {"1 STORAGE", "2 SYSTEM", "3 JOBS"};
- struct app *a = app->model;
- const struct tui_mouse *mo = &m->mouse;
- int idx, row, height;
+static bool mouse_event(tui_app *ui, const tui_msg *m) {
+ app *a = ui->model;
+ const tui_mouse *mo = &m->mouse;
+ tui_rect r = table_rect(m->w, m->h, a->tab);
+ int idx, row;
- height = (a->tab == 0 ? m->h - 8 : m->h - 6);
- if (height < 1)
- height = 1;
if (mo->button == 64 || mo->button == 65) {
- wheel(a, mo->button == 64 ? -1 : 1, height);
+ wheel(a, mo->button == 64 ? -1 : 1, table_rows(m->w, m->h, a->tab));
return true;
}
if (mo->release || mo->button != 0)
return false;
if (mo->y == 1) {
- idx = tui_tabs_hit(mo->x, views, 3);
+ idx = tui_tabs_hit(mo->x, tab_labels, 7);
if (idx < 0)
return false;
a->tab = idx;
return true;
}
- if (a->tab == 0 && mo->y == 3) {
- if (mo->x >= 1 && mo->x <= 5)
- a->sub = 0;
- else if (mo->x >= 7 && mo->x <= 11)
- a->sub = 1;
- else if (mo->x >= 13 && mo->x <= 18)
- a->sub = 2;
- else if (mo->x >= 20 && mo->x <= 24)
- a->sub = 3;
- else
- return false;
- return true;
+ if (a->tab == 0 && mo->y == r.y - 2) {
+ /* The drawn labels, without their trailing space. */
+ static const tui_rect area[4] = {
+ {1, 0, 5, 1}, {7, 0, 5, 1}, {13, 0, 6, 1}, {20, 0, 5, 1}};
+
+ for (int i = 0; i < 4; i++)
+ if (tui_rect_hit((tui_rect){area[i].x, area[i].y + r.y - 2,
+ area[i].w, area[i].h},
+ mo->x, mo->y)) {
+ a->sub = i;
+ return true;
+ }
+ return false;
}
- if (a->tab == 0 && mo->y >= 6) {
- row = a->storage.vp.top + (mo->y - 6);
- if (row < a->info[a->sub].nsub) {
- a->storage.vp.sel = row;
- return true;
- }
- } else if (a->tab == 2 && mo->y >= 4) {
- row = a->jobs.vp.top + (mo->y - 4);
- if (row < a->sys.njobs) {
- a->jobs.vp.sel = row;
- return true;
- }
+ if (!tui_rect_hit(r, mo->x, mo->y) || mo->y == r.y)
+ return false;
+ row = vp_of(a)->top + (mo->y - r.y - 1);
+ if (row < vrows(a)) {
+ vp_of(a)->sel = row;
+ return true;
}
return false;
}
-static bool update(struct tui_app *app, const struct tui_msg *m) {
- struct app *a = app->model;
- int rows, height;
+static bool update(tui_app *ui, const tui_msg *m) {
+ app *a = ui->model;
+ int height;
if (a->help) {
if (m->type == TUI_MSG_KEY && (m->key == '?' || m->key == TUI_KEY_ESC ||
@@ -989,8 +1809,10 @@ static bool update(struct tui_app *app, const struct tui_msg *m) {
return true;
}
if (a->popup) {
- if (m->type == TUI_MSG_KEY)
+ if (m->type == TUI_MSG_KEY) {
a->popup = false;
+ a->tcb_popup = false;
+ }
return true;
}
if (m->type == TUI_MSG_TICK) {
@@ -1001,12 +1823,50 @@ static bool update(struct tui_app *app, const struct tui_msg *m) {
if (m->type == TUI_MSG_RESIZE)
return true;
if (m->type == TUI_MSG_MOUSE)
- return mouse_event(app, m);
+ return mouse_event(ui, m);
if (m->type != TUI_MSG_KEY)
return false;
+ if (a->filtering || a->commanding) {
+ tui_input *in = a->filtering ? &a->fin : &a->cin;
+
+ if (m->key == TUI_KEY_ESC || m->key == 0x03) {
+ if (a->filtering) {
+ a->fin = (tui_input){};
+ filter_changed(a);
+ }
+ a->cin = (tui_input){};
+ a->filtering = false;
+ a->commanding = false;
+ } else if (m->key == '\r' || m->key == '\n') {
+ if (a->commanding)
+ run_command(a, a->cin.buf);
+ a->cin = (tui_input){};
+ a->filtering = false;
+ a->commanding = false;
+ } else {
+ (void)tui_input_key(in, m->key);
+ if (a->filtering)
+ filter_changed(a);
+ }
+ return true;
+ }
+
+ if (m->key == '/' || m->key == ':') {
+ tui_input *in = m->key == '/' ? &a->fin : &a->cin;
+
+ if (m->key == '/')
+ a->filtering = true;
+ else
+ a->commanding = true;
+ *in = (tui_input){};
+ in->focus = true;
+ return true;
+ }
+
if (m->key == 'q' || m->key == TUI_KEY_ESC || m->key == 0x03) {
- app->quit = true;
+ log_stop(a);
+ ui->quit = true;
return false;
}
if (m->key == '?') {
@@ -1017,6 +1877,14 @@ static bool update(struct tui_app *app, const struct tui_msg *m) {
a->paused = !a->paused;
return true;
}
+ if (m->key == 't' && a->tab == 0 && a->sub == 3) {
+ a->pvt_fold = !a->pvt_fold;
+ return true;
+ }
+ if (m->key == 'i') {
+ a->inspector = !a->inspector;
+ return true;
+ }
if (m->key == 'r') {
collect(a);
return true;
@@ -1033,20 +1901,35 @@ static bool update(struct tui_app *app, const struct tui_msg *m) {
return true;
}
if (m->key == TUI_KEY_TAB) {
- a->tab = (a->tab + 1) % 4;
+ a->tab = (a->tab + 1) % 7;
return true;
}
if (m->key == TUI_KEY_BACKTAB) {
- a->tab = (a->tab + 3) % 4;
+ a->tab = (a->tab + 6) % 7;
return true;
}
- if (a->tab == 0 && m->key >= '1' && m->key <= '4') {
- a->sub = m->key - '1';
- a->storage.vp.sel = 0;
- a->storage.vp.top = 0;
+ if (m->key >= '1' && m->key <= '7') {
+ if (a->tab == 0 && m->key <= '4') { /* 1-4 are the areas here */
+ a->sub = m->key - '1';
+ a->storage.vp.sel = 0;
+ a->storage.vp.top = 0;
+ a->pvt_vp.sel = 0;
+ a->pvt_vp.top = 0;
+ return true;
+ }
+ a->tab = m->key - '1';
+ if (a->tab == 4)
+ a->have_ps = uss_ps_read(&a->ps);
+ else if (a->tab == 5)
+ a->have_fs = uss_fs_read(&a->fs);
+ else if (a->tab == 6) {
+ if (!a->log_on)
+ log_start(a);
+ log_poll(a);
+ }
return true;
}
- if ((m->key == 's' || m->key == 'S') && a->tab != 1) {
+ if ((m->key == 's' || m->key == 'S') && (a->tab == 0 || a->tab == 2)) {
int *key = a->tab == 0 ? &a->sub_sort : &a->job_sort;
int *dir = a->tab == 0 ? &a->sub_dir : &a->job_dir;
int n = a->tab == 0 ? SS_COUNT : JS_COUNT;
@@ -1057,24 +1940,21 @@ static bool update(struct tui_app *app, const struct tui_msg *m) {
*dir = -*dir;
return true;
}
- if (a->tab == 0 && (m->key == '\r' || m->key == '\n') &&
- a->info[a->sub].nsub > 0) {
+ if (a->tab == 0 && (m->key == '\r' || m->key == '\n') && vrows(a) > 0) {
a->popup = true;
+ a->tcb_popup = folded(a);
return true;
}
- rows = a->tab == 0 ? a->info[a->sub].nsub : a->sys.njobs;
- height = a->tab == 0 ? m->h - 8 : m->h - 6;
+ height = vheight(a, m->h);
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);
+ if (a->tab == 0 || a->tab == 2 || a->tab == 6)
+ return tui_viewport_key(vp_of(a), m->key, vrows(a), height);
return false;
}
-static void sys_fill(struct zsys *z, const char *host) {
+static void sys_fill(zsys *z, const char *host) {
struct utsname u;
if (uname(&u) == 0) {
@@ -1085,9 +1965,9 @@ static void sys_fill(struct zsys *z, const char *host) {
}
static void run_tui(int interval) {
- static struct app a;
- struct tui t;
- struct tui_app ta;
+ static app a;
+ tui t;
+ tui_app ta;
memset(&a, 0, sizeof a);
if (gethostname(a.host, sizeof a.host - 1) != 0)
@@ -1101,6 +1981,10 @@ static void run_tui(int interval) {
a.storage.ncols = 8;
a.jobs.cols = job_cols;
a.jobs.ncols = 3;
+ a.pst.cols = ps_cols;
+ a.pst.ncols = 6;
+ a.fst.cols = fs_cols;
+ a.fst.ncols = 7;
if (!tui_open(&t)) {
(void)fprintf(stderr, "ztop: -d needs a terminal\n");
@@ -1115,6 +1999,7 @@ static void run_tui(int interval) {
ta.tick_ms = interval * 1000;
a.tapp = &ta;
tui_run(&t, &ta);
+ log_stop(&a); /* a signal can end the loop without the q path */
tui_close(&t);
}
@@ -1126,7 +2011,7 @@ static void run_oneshot(unsigned mask, bool want_sys, bool want_jobs,
int i;
for (i = 0; i < 4; i++) {
- struct vsm_info v;
+ vsm_info v;
if ((mask & (1u << i)) == 0)
continue;
@@ -1141,7 +2026,7 @@ static void run_oneshot(unsigned mask, bool want_sys, bool want_jobs,
printed = true;
}
if (want_page) {
- struct zpage p;
+ zpage p;
if (!zpage_read(&p)) {
(void)fprintf(stderr, "ztop: paging is only available on z/OS\n");
@@ -1154,7 +2039,7 @@ static void run_oneshot(unsigned mask, bool want_sys, bool want_jobs,
}
}
if (want_sys || want_jobs) {
- struct zsys z;
+ zsys z;
if (gethostname(host, sizeof host - 1) != 0)
(void)snprintf(host, sizeof host, "?");
@@ -1211,11 +2096,13 @@ int main(int argc, char **argv) {
usage(stderr);
return 2;
}
+ } else if (strcmp(argv[i], "-c") == 0) {
+ console_opt = true;
} else if (strcmp(argv[i], "-d") == 0) {
interactive = true;
if (i + 1 < argc && argv[i + 1][0] >= '0' &&
argv[i + 1][0] <= '9') {
- long secs = strtol(argv[++i], NULL, 10);
+ long secs = strtol(argv[++i], nullptr, 10);
interval = secs < 1 ? 1 : secs > 60 ? 60 : (int)secs;
}
diff --git a/tests/__pycache__/screen.cpython-315-pytest-9.1.1.pyc b/tests/__pycache__/screen.cpython-315-pytest-9.1.1.pyc
deleted file mode 100644
index ff0f12c..0000000
--- a/tests/__pycache__/screen.cpython-315-pytest-9.1.1.pyc
+++ /dev/null
Binary files differ
diff --git a/tests/screen.py b/tests/screen.py
index 844ec7f..431d423 100644
--- a/tests/screen.py
+++ b/tests/screen.py
@@ -19,17 +19,37 @@ import time
W, H = 100, 30
grid = [[' '] * W for _ in range(H)]
row = col = 0
+# G0 set: DEC Special Graphics letters when ESC(0 selected it, else ASCII.
+# The library draws its frame that way; paint what the terminal would show.
+acs = False
+pending = b''
+DEC = {'l': '\u250c', 'k': '\u2510', 'm': '\u2514', 'j': '\u2518',
+ 'q': '\u2500', 'x': '\u2502', 't': '\u251c', 'u': '\u2524',
+ 'w': '\u252c', 'v': '\u2534', 'n': '\u253c', 'a': '\u2592'}
def feed(data):
- global row, col
+ global row, col, acs, pending
+ data = pending + data
+ pending = b''
i = 0
while i < len(data):
b = data[i]
- if b == 0x1b and i + 1 < len(data) and data[i + 1] == ord('['):
+ if b == 0x1b and i + 1 >= len(data):
+ pending = data[i:]
+ return
+ if b == 0x1b and data[i + 1] == ord('('):
+ if i + 3 > len(data):
+ pending = data[i:]
+ return
+ acs = data[i + 2] == ord('0')
+ i += 3
+ continue
+ if b == 0x1b and data[i + 1] == ord('['):
j = i + 2
while j < len(data) and not (0x40 <= data[j] <= 0x7e):
j += 1
if j >= len(data):
+ pending = data[i:]
return
params = data[i + 2:j].decode('latin1')
final = chr(data[j])
@@ -51,7 +71,8 @@ def feed(data):
row = min(H - 1, row + 1)
elif b >= 0x20:
if row < H and col < W:
- grid[row][col] = chr(b)
+ c = chr(b)
+ grid[row][col] = DEC.get(c, c) if acs else c
col += 1
i += 1
@@ -77,10 +98,14 @@ def pump(t):
return
feed(d)
+def show(what):
+ print('===', what)
+ for line in grid:
+ print(''.join(line).rstrip())
+
pump(2.0)
+show('initial')
for k in [b'\t', b'\t', b'\t', b'\t', b'?', b'?', b'q']:
os.write(fd, k)
pump(1.0)
- print('=== after', k)
- for line in grid:
- print(''.join(line).rstrip())
+ show(f'after {k!r}')
diff --git a/tests/test_mdb.c b/tests/test_mdb.c
new file mode 100644
index 0000000..0e63255
--- /dev/null
+++ b/tests/test_mdb.c
@@ -0,0 +1,90 @@
+/**
+ * @file test_mdb.c
+ * @brief The message-block walk, against blocks built byte by byte.
+ *
+ * The shape is the one IEAVM105 documents: a 12-byte header, then objects
+ * of two bytes of length and two of type. A general object carries the
+ * job name at +48 and a text object its line at +9.
+ */
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "mdb.h"
+
+/** A general object: 56 bytes, job name at +48. */
+static void put_general(unsigned char *p, const char *job) {
+ p[0] = 0;
+ p[1] = 56;
+ p[2] = 0;
+ p[3] = 1;
+ (void)memset(p + 48, ' ', 8);
+ (void)memcpy(p + 48, job, strlen(job));
+}
+
+/** A text object: the line starts at +9, so the length is 9 + the line. */
+static void put_text(unsigned char *p, const char *line) {
+ int n = (int)strlen(line);
+
+ p[0] = (unsigned char)((9 + n) >> 8);
+ p[1] = (unsigned char)(9 + n);
+ p[2] = 0;
+ p[3] = 4;
+ (void)memcpy(p + 9, line, (size_t)n);
+}
+
+int main(void) {
+ static unsigned char mdb[512];
+ char job[16];
+ char text[MDB_TEXT_MAX];
+
+ /* Job and line, in the order the service writes them. */
+ (void)memset(mdb, 0, sizeof mdb);
+ put_general(mdb + 12, "JOB1");
+ put_text(mdb + 12 + 56, "IEF403I JOB1 - STARTED");
+ assert(mdb_line((const char *)mdb, 12 + 56 + 9 + 22, job, sizeof job, text,
+ sizeof text));
+ assert(strcmp(job, "JOB1") == 0);
+ assert(strcmp(text, "IEF403I") == 0); /* trimmed at the first blank */
+
+ /* A line of one word keeps the word. */
+ (void)memset(mdb, 0, sizeof mdb);
+ put_general(mdb + 12, "J2");
+ put_text(mdb + 12 + 56, "STARTED");
+ assert(mdb_line((const char *)mdb, 12 + 56 + 9 + 7, job, sizeof job, text,
+ sizeof text));
+ assert(strcmp(job, "J2") == 0 && strcmp(text, "STARTED") == 0);
+
+ /* No text object: nothing to show, and the job is still known. */
+ (void)memset(mdb, 0, sizeof mdb);
+ put_general(mdb + 12, "J3");
+ assert(!mdb_line((const char *)mdb, 12 + 56, job, sizeof job, text,
+ sizeof text));
+ assert(strcmp(job, "J3") == 0 && text[0] == '\0');
+
+ /* A length that runs past the copy stops the walk: the block comes
+ * from another address space, so its lengths are input. */
+ (void)memset(mdb, 0, sizeof mdb);
+ put_text(mdb + 12, "SHOULD NOT APPEAR");
+ mdb[12] = 0x7F; /* claims 32k */
+ mdb[13] = 0xFF;
+ assert(!mdb_line((const char *)mdb, 12 + 9 + 16, job, sizeof job, text,
+ sizeof text));
+
+ /* Empty and short blocks are refused, not walked. */
+ assert(!mdb_line(nullptr, 8, job, sizeof job, text, sizeof text));
+ assert(!mdb_line((const char *)mdb, 8, job, sizeof job, text, sizeof text));
+ assert(!mdb_line((const char *)mdb, 0, job, sizeof job, text, sizeof text));
+
+ /* A zero-length object ends the walk without reading further. */
+ (void)memset(mdb, 0, sizeof mdb);
+ mdb[12] = 0;
+ mdb[13] = 0;
+ mdb[14] = 0;
+ mdb[15] = 4;
+ assert(
+ !mdb_line((const char *)mdb, 32, job, sizeof job, text, sizeof text));
+
+ (void)printf("test_mdb: ok\n");
+ return 0;
+}
diff --git a/tests/test_sys.c b/tests/test_sys.c
index b807859..ab20ddc 100644
--- a/tests/test_sys.c
+++ b/tests/test_sys.c
@@ -8,7 +8,7 @@
#include "sys.h"
int main(void) {
- struct zipl z;
+ zipl z;
/* CBT, IPLed at 17:02:47 on 21 September 2026 (day 264). */
assert(zipl_decode(0x0126264Fu, 6136760u, &z));
diff --git a/tests/test_vsm.c b/tests/test_vsm.c
index 371b7ad..284d9b6 100644
--- a/tests/test_vsm.c
+++ b/tests/test_vsm.c
@@ -48,7 +48,7 @@ static int fail_line(int line, const char *what) {
} while (0)
static int test_csa(void) {
- struct vsm_info v;
+ vsm_info v;
len = 0;
put32(2);
@@ -89,7 +89,7 @@ static int test_csa(void) {
}
static int test_merge(void) {
- struct vsm_info v;
+ vsm_info v;
len = 0;
put32(1);
@@ -108,8 +108,30 @@ static int test_merge(void) {
return 0;
}
+static int test_line16(void) {
+ vsm_info v;
+
+ len = 0;
+ put32(1);
+ desc(230, 0x08, 0, 8);
+ put32(2);
+ block(0x00FF0000, 0x1000); /* ends exactly at the line: below */
+ put32(0);
+ block(0x01000000, 0x1000); /* starts at the line: above */
+ put32(0);
+
+ vsm_reset(&v, VSM_CSA, VSM_FREE);
+ CHECK(vsm_parse_alloc(&v, buf, len));
+ CHECK(v.used == 0x2000);
+ CHECK(v.below == 0x1000);
+ CHECK(v.above == 0x1000);
+ CHECK(v.sub[0].below == 0x1000);
+ CHECK(v.sub[0].above == 0x1000);
+ return 0;
+}
+
static int test_pvt(void) {
- struct vsm_info v;
+ vsm_info v;
len = 0;
put32(1);
@@ -131,7 +153,7 @@ static int test_pvt(void) {
}
static int test_unalloc(void) {
- struct vsm_info v;
+ vsm_info v;
len = 0;
put32(2);
@@ -157,7 +179,7 @@ static int test_unalloc(void) {
}
static int test_bad(void) {
- struct vsm_info v;
+ vsm_info v;
/* descriptor length below the documented minimum */
len = 0;
@@ -213,6 +235,7 @@ int main(void) {
rc |= test_csa();
rc |= test_merge();
+ rc |= test_line16();
rc |= test_pvt();
rc |= test_unalloc();
rc |= test_bad();
diff --git a/tui/Makefile b/tui/Makefile
index 7304500..89479e3 100644
--- a/tui/Makefile
+++ b/tui/Makefile
@@ -14,7 +14,7 @@
.SUFFIXES:
CC = cc
-CFLAGS = -std=c17 -O2 -Wall -Wextra -Wshadow -Wpedantic \
+CFLAGS = -std=c23 -O2 -Wall -Wextra -Wshadow -Wpedantic \
-D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200112L
AR = ar
diff --git a/tui/demo.c b/tui/demo.c
index 6e2e081..c8cf45c 100644
--- a/tui/demo.c
+++ b/tui/demo.c
@@ -6,7 +6,7 @@
#include "tui.h"
int main(void) {
- struct tui t;
+ tui t;
int x = 4;
if (!tui_open(&t)) {
diff --git a/tui/test_tui.c b/tui/test_tui.c
index 63a5e86..0a4950b 100644
--- a/tui/test_tui.c
+++ b/tui/test_tui.c
@@ -1,8 +1,12 @@
-/* Buffer-level tests for libtui: no terminal, no clock, no signals.
+/* Buffer-level tests for libtui: no terminal, no signals. The tick test
+ * uses a pipe and a real clock, because that is where the bug was.
* `make test` builds and runs this next to the library. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/select.h>
+#include <sys/wait.h>
+#include <unistd.h>
#include "tui.h"
@@ -16,12 +20,12 @@ static int fails;
} \
} while (0)
-static unsigned char cell(const struct tui *t, int x, int y) {
+static unsigned char cell(const 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;
+ tui t;
memset(&t, 0, sizeof t);
CHECK(tui_alloc(&t, 20, 6));
@@ -55,7 +59,7 @@ static void test_buffer(void) {
}
static void test_viewport(void) {
- struct tui_viewport v = {0, 0};
+ tui_viewport v = {0, 0};
tui_viewport_clamp(&v, 10, 3);
CHECK(v.sel == 0 && v.top == 0);
@@ -85,23 +89,26 @@ static void test_tabs(void) {
CHECK(act == 2);
CHECK(!tui_tabs_key('x', &act, 3));
- struct tui t;
+ 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(x == 5 + 2 + 5 + 2 + 7);
CHECK(cell(&t, 0, 0) == ' ');
CHECK(cell(&t, 1, 0) == 'o');
CHECK(cell(&t, 6, 0) == ' ');
- CHECK(cell(&t, 7, 0) == 't');
+ CHECK(cell(&t, 7, 0) == ' ');
+ CHECK(cell(&t, 8, 0) == 't');
+ CHECK(tui_tabs_hit(8, labels, 3) == 1);
+ CHECK(tui_tabs_hit(6, labels, 3) == -1);
free(t.cur);
free(t.old);
}
static void test_input(void) {
- struct tui_input in;
+ tui_input in;
memset(&in, 0, sizeof in);
in.focus = true;
@@ -129,33 +136,149 @@ static void called(void *ctx, int row, int col, char *buf, size_t len) {
}
static void test_table(void) {
- static const struct tui_col cols[2] = {
+ static const tui_col cols[2] = {
{"A", 5, false},
{"B", 4, true},
};
- struct tui_table tb = {cols, 2, {0, 0}};
- struct tui t;
+ tui_table tb = {cols, 2, {0, 0}};
+ 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);
+ tui_table_draw(&t, (tui_rect){0, 0, 20, 5}, &tb, 3, called, nullptr,
+ nullptr);
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);
+ tui_table_draw(&t, (tui_rect){0, 0, 20, 5}, &tb, 3, called, nullptr,
+ nullptr);
CHECK(cell(&t, 6, 3) == 'r'); /* third row is last visible */
free(t.cur);
free(t.old);
}
+/* Layout, sparkline and keymap: geometry is computed once and shared. */
+static void test_widgets(void) {
+ tui t;
+ tui_rect a, b, r = {0, 0, 80, 24};
+ static const unsigned char samples[] = {0, 50, 100};
+ static const tui_binding km[] = {
+ {"q", "quit", "screen", 0xFu, true},
+ };
+
+ tui_split_v(r, 3, &a, &b);
+ CHECK(a.y == 0 && a.h == 3 && b.y == 3 && b.h == 21);
+ tui_split_h(b, 50, &a, &b);
+ CHECK(a.x == 0 && a.w == 50 && b.x == 50 && b.w == 30);
+ a = tui_inset(r, 2, 1);
+ CHECK(a.x == 2 && a.y == 1 && a.w == 76 && a.h == 22);
+ CHECK(tui_rect_hit(a, 2, 1));
+ CHECK(!tui_rect_hit(a, 1, 1));
+ CHECK(!tui_rect_hit(a, 78, 1));
+
+ memset(&t, 0, sizeof t);
+ CHECK(tui_alloc(&t, 40, 6));
+ tui_clear(&t);
+ tui_sparkline(&t, 0, 0, samples, 3, TUI_ACCENT);
+ CHECK(cell(&t, 0, 0) == ' ');
+ CHECK(cell(&t, 1, 0) == '=');
+ CHECK(cell(&t, 2, 0) == '%');
+ tui_keymap_footer(&t, 0, 1, 40, km, 1, 0);
+ CHECK(cell(&t, 1, 1) == 'q');
+ free(t.cur);
+ free(t.old);
+}
+
+typedef struct tick_state {
+ int ticks;
+ int keys;
+} tick_state;
+
+static void nothing(void *model, tui *t) {
+ (void)model, (void)t;
+}
+
+static bool tick_update(tui_app *app, const tui_msg *m) {
+ tick_state *s = app->model;
+
+ if (m->type == TUI_MSG_TICK) {
+ s->ticks++;
+ app->quit = s->ticks >= 2;
+ return false;
+ }
+ if (m->type == TUI_MSG_KEY) {
+ s->keys++;
+ if (s->keys >= 100) /* the bug: keys all the way and not a tick */
+ app->quit = true;
+ }
+ return false;
+}
+
+/* The interval is a deadline, not a wait restarted by every key. A child
+ * holds a key down at 5 ms intervals; with the old code the 50 ms select
+ * never expired and no tick arrived. */
+static void test_tick(void) {
+ tui t;
+ tui_app app;
+ tick_state s;
+ int p[2];
+ pid_t pid;
+
+ memset(&t, 0, sizeof t);
+ memset(&app, 0, sizeof app);
+ memset(&s, 0, sizeof s);
+ CHECK(pipe(p) == 0);
+ CHECK(tui_alloc(&t, 20, 6));
+ t.fd_in = p[0];
+ t.fd_out = -1; /* nothing redraws, so nothing is flushed */
+ app.model = &s;
+ app.update = tick_update;
+ app.view = nothing;
+ app.tick_ms = 50;
+
+ pid = fork();
+ CHECK(pid >= 0);
+ if (pid == 0) {
+ int idle[2];
+
+ (void)close(p[0]);
+ if (pipe(idle) != 0)
+ _exit(1);
+ for (int i = 0; i < 200; i++) {
+ /* select is the sleep this build has: nanosleep is not
+ * declared on z/OS, and nfds 0 with no set returns at once. */
+ fd_set f;
+ struct timeval gap = {0, 5000};
+
+ if (write(p[1], "j", 1) != 1)
+ break;
+ FD_ZERO(&f);
+ FD_SET(idle[0], &f);
+ (void)select(idle[0] + 1, &f, nullptr, nullptr, &gap);
+ }
+ _exit(0);
+ }
+ (void)close(p[1]);
+ tui_run(&t, &app);
+ CHECK(s.ticks == 2);
+ CHECK(s.keys < 100);
+
+ (void)close(p[0]); /* the writer stops on the next write */
+ (void)waitpid(pid, nullptr, 0);
+ free(t.cur);
+ free(t.old);
+}
+
int main(void) {
test_buffer();
test_viewport();
test_tabs();
test_input();
test_table();
+ test_widgets();
+ test_tick();
(void)printf("test_tui: %s\n", fails == 0 ? "ok" : "FAILED");
return fails != 0;
}
diff --git a/tui/tui.c b/tui/tui.c
index 6ab7de4..f17e718 100644
--- a/tui/tui.c
+++ b/tui/tui.c
@@ -13,6 +13,7 @@
#include <string.h>
#include <sys/ioctl.h>
#include <sys/select.h>
+#include <time.h>
#include <unistd.h>
#ifdef __MVS__
@@ -34,7 +35,7 @@
#define CLEAR ESCS "[H" ESCS "[2J"
#define RESET ESCS "[0m"
-static struct tui *g_tui;
+static tui *g_tui;
static volatile sig_atomic_t g_winch;
static void wr(int fd, const void *buf, size_t n) {
@@ -51,11 +52,12 @@ static void wr(int fd, const void *buf, size_t n) {
}
}
-static void restore(struct tui *t) {
+static void restore(tui *t) {
if (!t->open)
return;
- wr(t->fd_out, RESET CUR_ON MOUSE_OFF ALT_OFF,
- strlen(RESET CUR_ON MOUSE_OFF ALT_OFF));
+ /* Leave the graphics character set even if a signal cut a frame short. */
+ wr(t->fd_out, RESET ESCS "(B" CUR_ON MOUSE_OFF ALT_OFF,
+ strlen(RESET ESCS "(B" CUR_ON MOUSE_OFF ALT_OFF));
(void)tcsetattr(t->fd_in, TCSANOW, &t->orig);
}
@@ -65,19 +67,19 @@ static void on_winch(int sig) {
}
static void on_term(int sig) {
- if (g_tui != NULL)
+ if (g_tui != nullptr)
restore(g_tui);
_exit(128 + sig);
}
-static void out_flush(struct tui *t) {
+static void out_flush(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) {
+static void out(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) {
@@ -88,11 +90,11 @@ static void out(struct tui *t, const char *s, size_t n) {
t->olen += (int)n;
}
-static void outs(struct tui *t, const char *s) {
+static void outs(tui *t, const char *s) {
out(t, s, strlen(s));
}
-static void outf(struct tui *t, const char *fmt, ...) {
+static void outf(tui *t, const char *fmt, ...) {
char b[64];
va_list ap;
int n;
@@ -104,8 +106,8 @@ static void outf(struct tui *t, const char *fmt, ...) {
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];
+static void sgr(tui *t, int fg, int bg, int attr) {
+ char b[64];
int n = snprintf(b, sizeof b, "%s[0", ESCS);
if (attr & TUI_BOLD)
@@ -116,7 +118,14 @@ static void sgr(struct tui *t, int fg, int bg, int attr) {
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);
+ if (fg == TUI_COLOR_DEFAULT)
+ n += snprintf(b + n, sizeof b - (size_t)n, ";39");
+ else
+ n += snprintf(b + n, sizeof b - (size_t)n, ";38;5;%d", fg);
+ if (bg == TUI_COLOR_DEFAULT)
+ n += snprintf(b + n, sizeof b - (size_t)n, ";49m");
+ else
+ n += snprintf(b + n, sizeof b - (size_t)n, ";48;5;%dm", bg);
out(t, b, (size_t)n);
}
@@ -135,7 +144,7 @@ static bool cpr_size(int in, int outfd, int *w, int *h) {
FD_ZERO(&f);
FD_SET(in, &f);
- int r = select(in + 1, &f, NULL, NULL, &tv);
+ int r = select(in + 1, &f, nullptr, nullptr, &tv);
if (r < 0 && errno == EINTR)
continue;
if (r <= 0)
@@ -180,7 +189,7 @@ static bool cpr_size(int in, int outfd, int *w, int *h) {
return true;
}
-static void probe_size(struct tui *t, int *w, int *h) {
+static void probe_size(tui *t, int *w, int *h) {
struct winsize ws;
*w = 80;
@@ -192,9 +201,9 @@ static void probe_size(struct tui *t, int *w, int *h) {
} 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)
+ if (c != nullptr && atoi(c) > 0)
*w = atoi(c);
- if (l != NULL && atoi(l) > 0)
+ if (l != nullptr && atoi(l) > 0)
*h = atoi(l);
}
if (*w > TUI_MAX_W)
@@ -207,8 +216,8 @@ static void probe_size(struct tui *t, int *w, int *h) {
*h = 24;
}
-bool tui_alloc(struct tui *t, int w, int h) {
- struct tui_cell *cur, *old;
+bool tui_alloc(tui *t, int w, int h) {
+ tui_cell *cur, *old;
if (w < 2)
w = 2;
@@ -220,7 +229,7 @@ bool tui_alloc(struct tui *t, int w, int 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) {
+ if (cur == nullptr || old == nullptr) {
free(cur);
free(old);
return false;
@@ -236,7 +245,7 @@ bool tui_alloc(struct tui *t, int w, int h) {
return true;
}
-bool tui_resize(struct tui *t) {
+bool tui_resize(tui *t) {
int w, h;
probe_size(t, &w, &h);
@@ -245,10 +254,39 @@ bool tui_resize(struct tui *t) {
return tui_alloc(t, w, h);
}
-bool tui_open(struct tui *t) {
+/* z/OS C runtime prefers sigaction(); plain signal() is not used. */
+static void install_signal(int sig, void (*fn)(int)) {
+ struct sigaction sa = {};
+
+ sa.sa_handler = fn;
+ (void)sigemptyset(&sa.sa_mask);
+ (void)sigaction(sig, &sa, nullptr);
+}
+
+/* DEC Special Graphics are VT100 core, but a terminal we do not recognise
+ * is not worth the risk: `lqqqk` where a corner should be is worse than
+ * `+----+`. This is the one place the glyph backend is chosen. */
+static bool term_glyphs(void) {
+ static const char *const ok[] = {
+ "xterm", "screen", "tmux", "rxvt", "vt100", "vt220",
+ "linux", "ansi", "cygwin", "alacrit", "foot", "wezterm",
+ "kitty", "konsole", "putty", "gnome", "iterm", "st",
+ };
+ const char *term = getenv("TERM");
+
+ if (term == nullptr || term[0] == '\0')
+ return false;
+ for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++)
+ if (strncmp(term, ok[i], strlen(ok[i])) == 0)
+ return true;
+ return false;
+}
+
+bool tui_open(tui *t) {
struct termios r;
memset(t, 0, sizeof *t);
+ t->glyphs = term_glyphs();
t->fd_in = 0;
t->fd_out = 1;
if (!isatty(t->fd_in) || !isatty(t->fd_out))
@@ -267,54 +305,92 @@ bool tui_open(struct tui *t) {
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);
+ install_signal(SIGTERM, on_term);
+ install_signal(SIGINT, on_term);
+ install_signal(SIGHUP, on_term);
+ install_signal(SIGQUIT, on_term);
#ifdef SIGWINCH
- (void)signal(SIGWINCH, on_winch);
+ install_signal(SIGWINCH, on_winch);
#endif
outs(t, ALT_ON CUR_OFF CLEAR MOUSE_ON);
out_flush(t);
if (!tui_resize(t)) {
restore(t);
t->open = false;
- g_tui = NULL;
+ g_tui = nullptr;
return false;
}
return true;
}
-void tui_close(struct tui *t) {
+void tui_close(tui *t) {
if (!t->open)
return;
restore(t);
t->open = false;
- g_tui = NULL;
+ g_tui = nullptr;
free(t->cur);
free(t->old);
- t->cur = NULL;
- t->old = NULL;
+ t->cur = nullptr;
+ t->old = nullptr;
}
-void tui_size(struct tui *t, int *w, int *h) {
+void tui_size(tui *t, int *w, int *h) {
*w = t->w;
*h = t->h;
}
-void tui_clear(struct tui *t) {
+void tui_clear(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].fg = TUI_PLAIN.fg;
+ t->cur[i].bg = TUI_PLAIN.bg;
t->cur[i].attr = 0;
}
}
-void tui_fill(struct tui *t, int x, int y, int w, int h, char ch,
- tui_style st) {
+/* ---- layout primitives ----------------------------------------------- */
+
+void tui_split_v(tui_rect r, int top_h, tui_rect *top, tui_rect *bot) {
+ if (top_h < 0)
+ top_h = 0;
+ if (top_h > r.h)
+ top_h = r.h;
+ if (top != nullptr)
+ *top = (tui_rect){r.x, r.y, r.w, top_h};
+ if (bot != nullptr)
+ *bot = (tui_rect){r.x, r.y + top_h, r.w, r.h - top_h};
+}
+
+void tui_split_h(tui_rect r, int left_w, tui_rect *left, tui_rect *right) {
+ if (left_w < 0)
+ left_w = 0;
+ if (left_w > r.w)
+ left_w = r.w;
+ if (left != nullptr)
+ *left = (tui_rect){r.x, r.y, left_w, r.h};
+ if (right != nullptr)
+ *right = (tui_rect){r.x + left_w, r.y, r.w - left_w, r.h};
+}
+
+tui_rect tui_inset(tui_rect r, int dx, int dy) {
+ int nw = r.w - 2 * dx;
+ int nh = r.h - 2 * dy;
+
+ return (tui_rect){r.x + dx, r.y + dy, nw > 0 ? nw : 0, nh > 0 ? nh : 0};
+}
+
+bool tui_rect_hit(tui_rect r, int x, int y) {
+ if (x < r.x || x >= r.x + r.w)
+ return false;
+ if (y < r.y || y >= r.y + r.h)
+ return false;
+ return true;
+}
+
+void tui_fill(tui *t, int x, int y, int w, int h, char ch, tui_style st) {
if (x < 0) {
w += x;
x = 0;
@@ -330,7 +406,7 @@ void tui_fill(struct tui *t, int x, int y, int w, int h, char ch,
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;
+ 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;
@@ -340,11 +416,10 @@ void tui_fill(struct tui *t, int x, int y, int w, int h, char ch,
}
}
-void tui_put(struct tui *t, int x, int y, const char *s, int maxw,
- tui_style st) {
+void tui_put(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;
+ 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)
@@ -360,8 +435,8 @@ void tui_put(struct tui *t, int x, int y, const char *s, int maxw,
}
}
-void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st,
- const char *fmt, ...) {
+void tui_printf(tui *t, int x, int y, int maxw, tui_style st, const char *fmt,
+ ...) {
char b[512];
va_list ap;
@@ -371,27 +446,49 @@ void tui_printf(struct tui *t, int x, int y, int maxw, tui_style st,
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) {
- tui_box_frame(t, x, y, w, h, st, NULL, TUI_PLAIN);
+void tui_box(tui *t, int x, int y, int w, int h, tui_style st) {
+ tui_box_frame(t, x, y, w, h, st, nullptr, TUI_PLAIN);
}
-void tui_box_frame(struct tui *t, int x, int y, int w, int h, tui_style st,
+/* ---- line drawing ---------------------------------------------------- */
+
+/* A cell holds one byte, so a line is either a DEC Special Graphics letter
+ * (the terminal draws the line) or the ASCII the frame has always used.
+ * The order is the order of the calls below and means nothing else. */
+enum { G_TL, G_TR, G_BL, G_BR, G_H, G_V, G_SHADE, G_COUNT };
+
+static char glyph(const tui *t, int g) {
+ static const char dec[] = {'l', 'k', 'm', 'j', 'q', 'x', 'a'};
+ static const char ascii[] = {'+', '+', '+', '+', '-', '|', '#'};
+
+ return t->glyphs ? dec[g] : ascii[g];
+}
+
+static void putg(tui *t, int x, int y, int g, tui_style st) {
+ char s[2] = {glyph(t, g), '\0'};
+
+ if (t->glyphs)
+ st.attr = (unsigned char)(st.attr | TUI_ACS);
+ tui_put(t, x, y, s, 1, st);
+}
+
+void tui_box_frame(tui *t, int x, int y, int w, int h, tui_style st,
const char *title, tui_style title_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);
+ putg(t, x + i, y, G_H, st);
+ putg(t, x + i, y + h - 1, G_H, 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);
+ putg(t, x, y + j, G_V, st);
+ putg(t, x + w - 1, y + j, G_V, 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);
- if (title != NULL && title[0] != '\0' && w > 6) {
+ putg(t, x, y, G_TL, st);
+ putg(t, x + w - 1, y, G_TR, st);
+ putg(t, x, y + h - 1, G_BL, st);
+ putg(t, x + w - 1, y + h - 1, G_BR, st);
+ if (title != nullptr && title[0] != '\0' && w > 6) {
char chip[64];
int n = (int)strlen(title);
int room = w - 6;
@@ -403,7 +500,7 @@ void tui_box_frame(struct tui *t, int x, int y, int w, int h, tui_style st,
}
}
-void tui_flush(struct tui *t) {
+void tui_flush(tui *t) {
int lfg = -1, lbg = -1, la = -1;
if (!t->open)
@@ -414,8 +511,8 @@ void tui_flush(struct tui *t) {
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;
+ tui_cell *row = t->cur + (size_t)y * (size_t)t->w;
+ tui_cell *orow = t->old + (size_t)y * (size_t)t->w;
int x = 0;
while (x < t->w) {
@@ -432,12 +529,20 @@ void tui_flush(struct tui *t) {
x++;
outf(t, "%s[%d;%dH", ESCS, y + 1, start + 1);
for (int i = start; i < x; i++) {
+ bool acs = (row[i].attr & TUI_ACS) != 0;
+
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;
}
+ /* An SGR reset does not leave the graphics set, so this is
+ * tracked apart from the colours. */
+ if (acs != t->acs_on) {
+ outs(t, acs ? ESCS "(0" : ESCS "(B");
+ t->acs_on = acs;
+ }
char c = (char)(row[i].ch != 0 ? row[i].ch : ' ');
out(t, &c, 1);
}
@@ -455,12 +560,12 @@ int tui_tabs_hit(int x, const char *const *labels, int n) {
if (x >= at && x < at + len)
return i;
- at += len + 1;
+ at += len + 2; /* the gap drawn by tui_tabs_draw */
}
return -1;
}
-int tui_tabs_draw(struct tui *t, int x, int y, const char *const *labels, int n,
+int tui_tabs_draw(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;
@@ -468,19 +573,17 @@ int tui_tabs_draw(struct tui *t, int x, int y, const char *const *labels, int n,
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_META);
- x += 1;
- }
+ if (i + 1 < n)
+ x += 2; /* a gap, not a `|`: separators read as a DOS menu */
}
return x;
}
-void tui_rule(struct tui *t, int y, char ch, tui_style st) {
+void tui_rule(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) {
+static void shift_in(tui *t, int n) {
if (n >= t->inlen) {
t->inlen = 0;
return;
@@ -489,7 +592,7 @@ static void shift_in(struct tui *t, int n) {
t->inlen -= n;
}
-static int decode(struct tui *t) {
+static int decode(tui *t) {
unsigned char *b = t->in;
if (t->inlen == 0)
@@ -610,7 +713,7 @@ static int decode(struct tui *t) {
return TUI_KEY_NONE;
}
-int tui_key(struct tui *t, int timeout_ms) {
+int tui_key(tui *t, int timeout_ms) {
if (g_winch) {
g_winch = 0;
return TUI_KEY_RESIZE;
@@ -627,7 +730,7 @@ int tui_key(struct tui *t, int timeout_ms) {
}
int wait = (t->inlen > 0) ? 30 : timeout_ms;
fd_set f;
- struct timeval tv, *ptv = NULL;
+ struct timeval tv, *ptv = nullptr;
FD_ZERO(&f);
FD_SET(t->fd_in, &f);
@@ -636,7 +739,7 @@ int tui_key(struct tui *t, int timeout_ms) {
tv.tv_usec = (wait % 1000) * 1000;
ptv = &tv;
}
- int r = select(t->fd_in + 1, &f, NULL, NULL, ptv);
+ int r = select(t->fd_in + 1, &f, nullptr, nullptr, ptv);
if (r < 0) {
if (errno == EINTR)
continue;
@@ -665,21 +768,51 @@ int tui_key(struct tui *t, int timeout_ms) {
/* ---- messages and the application loop ------------------------------- */
-void tui_run(struct tui *t, struct tui_app *app) {
+/** @brief Set @p due to now + @p ms on the monotonic clock. */
+static void deadline(struct timespec *due, int ms) {
+ (void)clock_gettime(CLOCK_MONOTONIC, due);
+ due->tv_sec += ms / 1000;
+ due->tv_nsec += (long)(ms % 1000) * 1000000L;
+ if (due->tv_nsec >= 1000000000L) {
+ due->tv_nsec -= 1000000000L;
+ due->tv_sec++;
+ }
+}
+
+/** @brief Milliseconds from now until @p due; 0 once it has passed. */
+static int remaining(const struct timespec *due) {
+ struct timespec now;
+ long long ms;
+
+ (void)clock_gettime(CLOCK_MONOTONIC, &now);
+ ms = (long long)(due->tv_sec - now.tv_sec) * 1000 +
+ (long)(due->tv_nsec - now.tv_nsec) / 1000000L;
+ return ms < 0 ? 0 : (int)ms;
+}
+
+void tui_run(tui *t, tui_app *app) {
+ struct timespec due;
+ int tick = app->tick_ms;
+
app->quit = false;
app->view(app->model, t);
tui_flush(t);
+ if (tick > 0)
+ deadline(&due, tick);
for (;;) {
- int k = tui_key(t, app->tick_ms > 0 ? app->tick_ms : -1);
- struct tui_msg m;
+ /* The interval is a deadline, not a wait restarted by each key:
+ * a held key would otherwise starve the tick. */
+ int k = tui_key(t, tick > 0 ? remaining(&due) : -1);
+ tui_msg m;
m.key = 0;
m.w = t->w;
m.h = t->h;
if (k == TUI_KEY_NONE) {
- if (app->tick_ms <= 0)
+ if (tick <= 0)
continue;
m.type = TUI_MSG_TICK;
+ deadline(&due, tick);
} else if (k == TUI_KEY_RESIZE) {
(void)tui_resize(t);
m.type = TUI_MSG_RESIZE;
@@ -696,12 +829,17 @@ void tui_run(struct tui *t, struct tui_app *app) {
}
if (app->quit)
break;
+ if (app->tick_ms != tick) {
+ tick = app->tick_ms;
+ if (tick > 0)
+ deadline(&due, tick);
+ }
}
}
/* ---- viewport -------------------------------------------------------- */
-void tui_viewport_clamp(struct tui_viewport *v, int rows, int height) {
+void tui_viewport_clamp(tui_viewport *v, int rows, int height) {
if (rows < 0)
rows = 0;
if (height < 1)
@@ -720,13 +858,12 @@ void tui_viewport_clamp(struct tui_viewport *v, int rows, int height) {
v->top = 0;
}
-void tui_viewport_move(struct tui_viewport *v, int delta, int rows,
- int height) {
+void tui_viewport_move(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) {
+bool tui_viewport_key(tui_viewport *v, int key, int rows, int height) {
switch (key) {
case 'j':
case TUI_KEY_DOWN:
@@ -759,9 +896,31 @@ bool tui_viewport_key(struct tui_viewport *v, int key, int rows, int height) {
/* ---- 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) {
+/* A proportional thumb on the last free column, only when there is more to
+ * see than fits. */
+static void draw_scrollbar(tui *t, tui_rect r, int rows, int top, int height) {
+ int x = r.x + r.w;
+ int thumb_h, max_top, thumb_y;
+
+ if (rows <= height || r.w <= 2)
+ return;
+ if (x >= t->w)
+ x = r.x + r.w - 1;
+ thumb_h = height * height / rows;
+ if (thumb_h < 1)
+ thumb_h = 1;
+ max_top = rows - height;
+ thumb_y = max_top > 0 ? top * (height - thumb_h) / max_top : 0;
+ for (int i = 0; i < height; i++) {
+ int on = i >= thumb_y && i < thumb_y + thumb_h;
+
+ putg(t, x, r.y + 1 + i, on != 0 ? G_SHADE : G_V,
+ on != 0 ? TUI_ACCENT : TUI_META);
+ }
+}
+
+void tui_table_draw(tui *t, tui_rect r, const 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];
@@ -793,20 +952,21 @@ void tui_table_draw(struct tui *t, tui_rect r, const struct tui_table *tb,
if (height < 1)
return;
- struct tui_viewport vp = tb->vp;
+ 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;
+ tui_style st = rowstyle != nullptr ? 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);
+
+ fs.bg = TUI_SEL_BG;
tui_fill(t, r.x, y, r.w, 1, ' ', fs);
- st.attr = fs.attr;
+ st = fs;
} else {
tui_fill(t, r.x, y, r.w, 1, ' ', TUI_PLAIN);
}
@@ -816,7 +976,7 @@ void tui_table_draw(struct tui *t, tui_rect r, const struct tui_table *tb,
if (w > r.x + r.w - x)
w = r.x + r.w - x;
buf[0] = '\0';
- if (cell != NULL)
+ if (cell != nullptr)
cell(ctx, row, c, buf, sizeof buf);
if (tb->cols[c].right)
tui_printf(t, x, y, w, st, "%*s", w, buf);
@@ -827,9 +987,10 @@ void tui_table_draw(struct tui *t, tui_rect r, const struct tui_table *tb,
x += 1;
}
}
+ draw_scrollbar(t, r, rows, vp.top, height);
}
-bool tui_table_key(struct tui_table *tb, int key, int rows, int height) {
+bool tui_table_key(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);
@@ -854,8 +1015,7 @@ bool tui_tabs_key(int key, int *active, int n) {
/* ---- text input ------------------------------------------------------ */
-void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in,
- tui_style st) {
+void tui_input_draw(tui *t, tui_rect r, const 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);
@@ -866,7 +1026,7 @@ void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in,
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);
+ tui_style cur = TUI_STYLE(16, 252, 0);
int cx = r.x + 1 + in->pos - start;
if (cx < r.x + 1 + w) {
@@ -876,7 +1036,7 @@ void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in,
}
}
-bool tui_input_key(struct tui_input *in, int key) {
+bool tui_input_key(tui_input *in, int key) {
if (!in->focus)
return false;
if (key >= 32 && key < 127) {
@@ -930,50 +1090,110 @@ bool tui_input_key(struct tui_input *in, int key) {
/* ---- progress and status -------------------------------------------- */
-void tui_progress(struct tui *t, int x, int y, int width, int pct) {
+void tui_progress(tui *t, int x, int y, int width, int pct) {
tui_style st;
- int fill, room, i;
+ int fill, i;
- if (width < 4)
+ if (width < 2)
return;
- room = width - 2;
- fill = pct < 0 ? 0 : pct * room / 100;
- if (fill > room)
- fill = room;
+ fill = pct < 0 ? 0 : pct * width / 100;
+ if (fill > width)
+ fill = width;
st = pct < 0 ? TUI_META
: pct < 70 ? TUI_GOOD
: pct < 85 ? TUI_WARN
: TUI_BAD;
- tui_put(t, x, y, "[", 1, TUI_META);
- for (i = 0; i < room; i++)
- tui_put(t, x + 1 + i, y, i < fill ? "=" : " ", 1,
- i < fill ? st : TUI_META);
- tui_put(t, x + width - 1, y, "]", 1, TUI_META);
+ /* A track with a shaded fill, no brackets: `[#### ]` is the other
+ * thing that read as curses. */
+ for (i = 0; i < width; i++)
+ putg(t, x + i, y, i < fill ? G_SHADE : G_H, i < fill ? st : TUI_META);
}
-void tui_hints(struct tui *t, int x, int y, int maxw,
- const struct tui_hint *hints, int n) {
+void tui_keymap_footer(tui *t, int x, int y, int maxw, const tui_binding *km,
+ int n, int tab) {
+ unsigned bit = 1u << (unsigned)tab;
+
for (int i = 0; i < n; i++) {
- int kl = (int)strlen(hints[i].key);
- int ll = (int)strlen(hints[i].label);
+ int kl, ll;
+ if (!km[i].in_footer || (km[i].tabs & bit) == 0)
+ continue;
+ kl = (int)strlen(km[i].key);
+ ll = (int)strlen(km[i].label);
if (x + kl + ll + 4 > maxw)
break;
- tui_put(t, x, y, " ", 1, TUI_META);
- tui_printf(t, x + 1, y, kl, TUI_KEYCAP, "%s", hints[i].key);
- tui_put(t, x + 1 + kl, y, " ", 1, TUI_META);
- tui_printf(t, x + 2 + kl, y, ll, TUI_META, "%s", hints[i].label);
+ tui_put(t, x, y, " ", 1, TUI_BAR);
+ tui_printf(t, x + 1, y, kl, TUI_KEYCAP, "%s", km[i].key);
+ tui_put(t, x + 1 + kl, y, " ", 1, TUI_BAR);
+ tui_printf(t, x + 2 + kl, y, ll, TUI_BAR, "%s", km[i].label);
x += kl + ll + 3;
}
}
-void tui_statusbar(struct tui *t, const char *left, const char *right) {
+void tui_keymap_help(tui *t, const tui_binding *km, int n, const char *title) {
+ int w = t->w < 68 ? t->w - 2 : 66;
+ int h = t->h < 20 ? t->h - 2 : 18;
+ int x = (t->w - w) / 2;
+ int y = (t->h - h) / 2;
+ const char *group = nullptr;
+ int row = y + 2;
+ int col_x = x + 2;
+
+ if (x < 0)
+ x = 0;
+ if (y < 0)
+ y = 0;
+ tui_fill(t, x, y, w, h, ' ', TUI_PLAIN);
+ tui_box_frame(t, x, y, w, h, TUI_ACCENT, title, TUI_ACCENT);
+ for (int i = 0; i < n && row < y + h - 2; i++) {
+ int kl, ll, need;
+
+ if (group == nullptr || strcmp(group, km[i].group) != 0) {
+ if (group != nullptr)
+ row += 2;
+ if (row >= y + h - 2)
+ break;
+ group = km[i].group;
+ tui_printf(t, x + 2, row++, w - 4, TUI_LABEL, "%s", group);
+ col_x = x + 2;
+ }
+ kl = (int)strlen(km[i].key);
+ ll = (int)strlen(km[i].label);
+ need = kl + ll + 4;
+ if (col_x + need > x + w - 2) {
+ row++;
+ col_x = x + 2;
+ if (row >= y + h - 2)
+ break;
+ }
+ tui_printf(t, col_x, row, kl, TUI_KEYCAP, "%s", km[i].key);
+ tui_printf(t, col_x + kl + 1, row, ll, TUI_META, "%s", km[i].label);
+ col_x += need;
+ }
+ tui_printf(t, x + 2, y + h - 2, w - 4, TUI_META, "press ? or ESC to close");
+}
+
+void tui_sparkline(tui *t, int x, int y, const unsigned char *vals, int n,
+ tui_style st) {
+ static const char ramp[] = " .:-=+*#%";
+
+ for (int i = 0; i < n; i++) {
+ unsigned v = vals[i] > 100u ? 100u : vals[i];
+ unsigned idx = (v * 8u + 50u) / 100u;
+ /* tui_put expects a terminated string, so the sample is one. */
+ char c[2] = {ramp[idx], '\0'};
+
+ tui_put(t, x + i, y, c, 1, st);
+ }
+}
+
+void tui_statusbar(tui *t, const char *left, const char *right) {
int y = t->h - 1;
tui_fill(t, 0, y, t->w, 1, ' ', TUI_BAR);
- if (left != NULL)
+ if (left != nullptr)
tui_printf(t, 1, y, t->w - 2, TUI_PLAIN, "%s", left);
- if (right != NULL) {
+ if (right != nullptr) {
int n = (int)strlen(right);
tui_printf(t, t->w - 1 - n, y, n, TUI_PLAIN, "%s", right);
}
diff --git a/tui/tui.h b/tui/tui.h
index c999eda..68404d4 100644
--- a/tui/tui.h
+++ b/tui/tui.h
@@ -7,187 +7,226 @@
* 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.
+ * bytes are stored, so a cell is one character wide: no UTF-8. The frame
+ * uses VT100 DEC Special Graphics when the terminal's TERM says it speaks
+ * them, and ASCII `+ - |` when it does not (or after tui_alloc alone). On
+ * z/OS the C compiler's EBCDIC literals are converted by the tty, which is
+ * why the escape byte 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 {
+/* The library is C, but a C++ program may include this header. */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct tui_cell {
unsigned char ch;
unsigned char fg;
unsigned char bg;
unsigned char attr;
-};
+} tui_cell;
-typedef struct {
- unsigned char fg; /**< 0-7, 7 is white */
- unsigned char bg; /**< 0-7, 0 is black */
+typedef struct tui_style {
+ unsigned char
+ fg; /**< xterm-256 index, TUI_COLOR_DEFAULT for the tty's own */
+ unsigned char
+ bg; /**< xterm-256 index, TUI_COLOR_DEFAULT for the tty's own */
unsigned char attr; /**< TUI_BOLD / TUI_REVERSE / TUI_DIM / TUI_UNDERLINE */
} tui_style;
-typedef struct {
+typedef struct tui_rect {
int x, y, w, h;
} tui_rect;
-#define TUI_BOLD 1u
-#define TUI_REVERSE 2u
-#define TUI_DIM 4u
-#define TUI_UNDERLINE 8u
+/** Attribute bits, packed into tui_cell.attr. */
+enum tui_attr : unsigned char {
+ TUI_BOLD = 1,
+ TUI_REVERSE = 2,
+ TUI_DIM = 4,
+ TUI_UNDERLINE = 8,
+ /** The byte is a DEC Special Graphics letter, drawn as a line glyph. */
+ TUI_ACS = 16,
+};
+
+/** The terminal's own foreground/background, as "SGR 39" and "SGR 49". */
+enum { TUI_COLOR_DEFAULT = 255 };
+
+/** Background of the selected table row. A soft surface, because reverse
+ * video is the thing that made this look like a curses application. */
+enum { TUI_SEL_BG = 236 };
#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)
-#define TUI_ACCENT TUI_STYLE(6, 0, TUI_BOLD)
-#define TUI_META TUI_STYLE(7, 0, TUI_DIM)
-#define TUI_KEYCAP TUI_STYLE(0, 6, 0)
-#define TUI_BAR TUI_STYLE(7, 4, 0)
+/* Blue, in xterm-256 indices: 25 navy, 18 a shade darker, 75 bright, 111
+ * pale, 61 slate, 189 a blue-grey body. The greens and reds are kept for
+ * meaning: free and used, healthy and broken. */
+#define TUI_PLAIN TUI_STYLE(189, TUI_COLOR_DEFAULT, 0)
+#define TUI_TITLE TUI_STYLE(252, 235, TUI_BOLD)
+/* Frames are quiet: a muted grey so the data, not the box, is what the eye
+ * lands on. Accent stays for the focused title and the selection. */
+#define TUI_FRAME TUI_STYLE(240, TUI_COLOR_DEFAULT, 0)
+#define TUI_LABEL TUI_STYLE(111, TUI_COLOR_DEFAULT, TUI_BOLD)
+#define TUI_GOOD TUI_STYLE(84, TUI_COLOR_DEFAULT, 0)
+#define TUI_WARN TUI_STYLE(222, TUI_COLOR_DEFAULT, 0)
+#define TUI_BAD TUI_STYLE(203, TUI_COLOR_DEFAULT, TUI_BOLD)
+#define TUI_TAB_ON TUI_STYLE(16, 75, TUI_BOLD)
+#define TUI_TAB_OFF TUI_STYLE(110, TUI_COLOR_DEFAULT, 0)
+#define TUI_ACCENT TUI_STYLE(75, TUI_COLOR_DEFAULT, TUI_BOLD)
+#define TUI_META TUI_STYLE(61, TUI_COLOR_DEFAULT, 0)
+#define TUI_KEYCAP TUI_STYLE(16, 111, TUI_BOLD)
+#define TUI_BAR TUI_STYLE(252, 235, 0)
+/* Above the byte range, so a key code never collides with a character.
+ * Every value is written out: the numbers are not a sequence to maintain. */
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,
- TUI_KEY_MOUSE,
+ TUI_KEY_UP = 257,
+ TUI_KEY_DOWN = 258,
+ TUI_KEY_LEFT = 259,
+ TUI_KEY_RIGHT = 260,
+ TUI_KEY_HOME = 261,
+ TUI_KEY_END = 262,
+ TUI_KEY_PGUP = 263,
+ TUI_KEY_PGDN = 264,
+ TUI_KEY_DEL = 265,
+ TUI_KEY_RESIZE = 266,
+ TUI_KEY_TAB = 267,
+ TUI_KEY_BACKTAB = 268,
+ TUI_KEY_MOUSE = 269,
};
-#define TUI_MAX_W 500
-#define TUI_MAX_H 200
+enum { TUI_MAX_W = 500 };
+enum { TUI_MAX_H = 200 };
+
+/* ---- layout primitives ----------------------------------------------- */
+
+/** @brief Cut @p r into a top band of @p top_h rows and the rest. */
+void tui_split_v(tui_rect r, int top_h, tui_rect *top, tui_rect *bot);
+/** @brief Cut @p r into a left band of @p left_w columns and the rest. */
+void tui_split_h(tui_rect r, int left_w, tui_rect *left, tui_rect *right);
+/** @brief Shrink @p r by @p dx columns and @p dy rows on every side. */
+tui_rect tui_inset(tui_rect r, int dx, int dy);
+/** @brief True when cell (@p x, @p y) is inside @p r. */
+bool tui_rect_hit(tui_rect r, int x, int y);
/** @brief One mouse event; coordinates are 0-based cells. */
-struct tui_mouse {
+typedef struct tui_mouse {
int x, y;
int button; /**< 0 left, 1 middle, 2 right, 64 wheel up, 65 wheel down */
bool release;
-};
+} tui_mouse;
-struct tui {
+typedef struct tui {
int w, h;
int fd_in, fd_out;
- struct tui_cell *cur;
- struct tui_cell *old;
+ tui_cell *cur;
+ tui_cell *old;
bool full;
bool open;
+ bool glyphs; /**< terminal speaks DEC Special Graphics */
+ bool acs_on; /**< G0 is currently the DEC graphics set */
struct termios orig;
unsigned char in[64];
int inlen;
char out[32768];
int olen;
- struct tui_mouse mouse;
-};
+ tui_mouse mouse;
+} tui;
-bool tui_alloc(struct tui *t, int w, int h);
-bool tui_open(struct tui *t);
-void tui_close(struct tui *t);
+bool tui_alloc(tui *t, int w, int h);
+bool tui_open(tui *t);
+void tui_close(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);
+bool tui_resize(tui *t);
+void tui_size(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_clear(tui *t);
+void tui_fill(tui *t, int x, int y, int w, int h, char ch, tui_style st);
+void tui_put(tui *t, int x, int y, const char *s, int maxw, tui_style st);
+void tui_printf(tui *t, int x, int y, int maxw, tui_style st, const char *fmt,
+ ...);
+void tui_box(tui *t, int x, int y, int w, int h, tui_style st);
/** @brief A box with a title set into its top border. */
-void tui_box_frame(struct tui *t, int x, int y, int w, int h, tui_style st,
+void tui_box_frame(tui *t, int x, int y, int w, int h, tui_style st,
const char *title, tui_style title_st);
-void tui_rule(struct tui *t, int y, char ch, tui_style st);
-void tui_flush(struct tui *t);
+void tui_rule(tui *t, int y, char ch, tui_style st);
+void tui_flush(tui *t);
/** @brief Wait up to @p timeout_ms (-1 = forever) for a key. */
-int tui_key(struct tui *t, int timeout_ms);
+int tui_key(tui *t, int timeout_ms);
/* ---- messages and the application loop ------------------------------- */
enum tui_msg_type { TUI_MSG_KEY, TUI_MSG_RESIZE, TUI_MSG_TICK, TUI_MSG_MOUSE };
-struct tui_msg {
+typedef 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_mouse mouse; /**< TUI_MSG_MOUSE */
-};
+ int key; /**< TUI_MSG_KEY: a byte or one of TUI_KEY_* */
+ int w, h; /**< TUI_MSG_RESIZE: the new size */
+ tui_mouse mouse; /**< TUI_MSG_MOUSE */
+} tui_msg;
-struct tui_app {
+typedef 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)(struct tui_app *app, const struct tui_msg *m);
+ bool (*update)(struct tui_app *app, const tui_msg *m);
/** Draw the model into the buffer. */
- void (*view)(void *model, struct tui *t);
+ void (*view)(void *model, tui *t);
int tick_ms; /**< 0 = no tick messages */
bool quit;
-};
+} tui_app;
/** @brief Run until the app sets @c quit (or the terminal goes away). */
-void tui_run(struct tui *t, struct tui_app *app);
+void tui_run(tui *t, tui_app *app);
/* ---- widgets --------------------------------------------------------- */
/** One scroll window: selected row, first visible row. */
-struct tui_viewport {
+typedef struct tui_viewport {
int sel;
int top;
-};
+} tui_viewport;
-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);
+void tui_viewport_clamp(tui_viewport *v, int rows, int height);
+void tui_viewport_move(tui_viewport *v, int delta, int rows, int height);
+bool tui_viewport_key(tui_viewport *v, int key, int rows, int height);
/** A column of a table. Width counts cells; right aligns numbers. */
-struct tui_col {
+typedef struct tui_col {
const char *title;
int width;
bool right;
-};
+} tui_col;
-struct tui_table {
- const struct tui_col *cols;
+typedef struct tui_table {
+ const tui_col *cols;
int ncols;
- struct tui_viewport vp;
-};
+ tui_viewport vp;
+} tui_table;
/** Render one cell into @p buf; the buffer is TUI_CELL_MAX bytes. */
-#define TUI_CELL_MAX 128
+enum { 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);
+void tui_table_draw(tui *t, tui_rect r, const 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);
+bool tui_table_key(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 tui_tabs_draw(tui *t, int x, int y, const char *const *labels, int n,
int active);
/** @brief Which tab covers cell @p x, or -1. Tabs start at column 0. */
@@ -196,33 +235,47 @@ int tui_tabs_hit(int x, const char *const *labels, int n);
/** Cycle tabs with left/right/tab/backtab; true when it was consumed. */
bool tui_tabs_key(int key, int *active, int n);
-/** @brief A key cap and its label, for the status bar. */
-struct tui_hint {
- const char *key;
- const char *label;
-};
+/** @brief One key binding, for the footer and the help overlay. */
+typedef struct tui_binding {
+ const char *key; /**< key cap text, e.g. "TAB", "s S", "/" */
+ const char *label; /**< short description */
+ const char *group; /**< section title in the help overlay */
+ unsigned tabs; /**< mask of tabs (1u << tab) where it applies */
+ bool in_footer; /**< show in the bottom status bar */
+} tui_binding;
-/** @brief Draw key caps and their labels along one row. */
-void tui_hints(struct tui *t, int x, int y, int maxw,
- const struct tui_hint *hints, int n);
+/** @brief Draw the footer hints of @p km that apply to @p tab. */
+void tui_keymap_footer(tui *t, int x, int y, int maxw, const tui_binding *km,
+ int n, int tab);
+
+/** @brief Draw the grouped help overlay from @p km. */
+void tui_keymap_help(tui *t, const tui_binding *km, int n, const char *title);
+
+/** @brief A sparkline of @p n samples, each 0-100, on row @p y. */
+enum { TUI_SPARK_LEN = 9 }; /* " .:-=+*#%" */
+void tui_sparkline(tui *t, int x, int y, const unsigned char *vals, int n,
+ tui_style st);
/** A single-line text input. */
-struct tui_input {
+typedef struct tui_input {
char buf[256];
int len;
int pos;
bool focus;
-};
+} tui_input;
-void tui_input_draw(struct tui *t, tui_rect r, const struct tui_input *in,
- tui_style st);
+void tui_input_draw(tui *t, tui_rect r, const 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);
+bool tui_input_key(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);
+void tui_progress(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);
+void tui_statusbar(tui *t, const char *left, const char *right);
+
+#ifdef __cplusplus
+}
+#endif
#endif