Skip to content
pi-c Artifact [e732276075]
Login

Artifact [e732276075]

Artifact e7322760751003963fda11262b98470be4cdf13a991fbc527aa312508367fd6e:


/* The settings panel's lines and keys; see panel.h. */
#include "tui/panel.h"

#include "tui/mjson.h"
#include "tui/theme.h"

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PNL_RESET "\x1b[0m"
#define PNL_BOLD "\x1b[1m"
#define PNL_ARROW "\xe2\x86\x92"
#define PNL_TICK "\xe2\x9c\x93"
#define PNL_DOT " \xc2\xb7 "
#define PNL_ELLIPSIS "\xe2\x80\xa6"
#define PNL_FIRST (-1000000L) /* pnl_move to the first row, and the last */
#define PNL_LAST 1000000L

/* ---- the list ---------------------------------------------------------------- */

static char *pnl_dup(const mj *v) {
    if (!v || v->kind != MJ_STR || !v->str) {
        return NULL;
    }
    return strdup(v->str);
}

static char *pnl_text(const mj *o, const char *key) {
    char *s = pnl_dup(mj_get(o, key));
    return s ? s : strdup("");
}

static void pnl_row_free(tui_setting *s) {
    free(s->id);
    free(s->key);
    free(s->group);
    free(s->name);
    free(s->kind);
    free(s->unit);
    free(s->def);
    free(s->def_label);
    free(s->description);
    free(s->applies);
    free(s->stored);
    free(s->value);
    for (size_t i = 0; i < s->nvalues; i++) {
        free(s->values[i]);
        free(s->labels[i]);
    }
    free(s->values);
    free(s->labels);
    memset(s, 0, sizeof *s);
}

void tui_settings_free(tui_settings *l) {
    for (size_t i = 0; i < l->n; i++) {
        pnl_row_free(&l->s[i]);
    }
    free(l->s);
    l->s = NULL;
    l->n = 0;
}

static int pnl_row(const mj *o, tui_setting *s) {
    const mj *vals = mj_get(o, "values"), *labs = mj_get(o, "labels"), *v;
    memset(s, 0, sizeof *s);
    s->id = pnl_text(o, "id");
    s->key = pnl_text(o, "key");
    s->group = pnl_text(o, "group");
    s->name = pnl_text(o, "name");
    s->kind = pnl_text(o, "kind");
    s->unit = pnl_dup(mj_get(o, "unit"));
    s->def = pnl_text(o, "default");
    s->def_label = pnl_text(o, "defaultLabel");
    s->description = pnl_text(o, "description");
    s->applies = pnl_text(o, "applies");
    s->stored = pnl_dup(mj_get(o, "stored"));
    s->value = pnl_text(o, "value");
    v = mj_get(o, "valid");
    s->valid = !v || v->kind != MJ_BOOL || v->num != 0;
    if ((v = mj_get(o, "min")) && v->kind == MJ_NUM) {
        s->min = (long long)v->num;
    }
    if ((v = mj_get(o, "max")) && v->kind == MJ_NUM) {
        s->max = (long long)v->num;
    }
    if (vals && vals->kind == MJ_ARR && vals->n) {
        s->values = calloc(vals->n, sizeof *s->values);
        s->labels = calloc(vals->n, sizeof *s->labels);
        if (!s->values || !s->labels) {
            return -1;
        }
        for (size_t i = 0; i < vals->n; i++) {
            const mj *lab = labs && labs->kind == MJ_ARR && i < labs->n ? labs->kids[i] : NULL;
            s->values[i] = pnl_dup(vals->kids[i]);
            s->labels[i] = lab ? pnl_dup(lab) : NULL;
            if (!s->values[i]) {
                s->values[i] = strdup("");
            }
            if (!s->labels[i]) {
                s->labels[i] = strdup(s->values[i] ? s->values[i] : "");
            }
            s->nvalues = i + 1;
            if (!s->values[i] || !s->labels[i]) {
                return -1;
            }
        }
    }
    return s->id && s->key && s->group && s->name && s->kind && s->def && s->def_label && s->description &&
                   s->applies && s->value
               ? 0
               : -1;
}

int tui_settings_parse(const char *json, tui_settings *out) {
    char err[64];
    mj *doc = json ? mj_parse(json, strlen(json), err, sizeof err) : NULL;
    const mj *rows, *ver, *unchanged;
    tui_settings l = {NULL, 0, -1};
    int rc = -1;
    if (!doc || doc->kind != MJ_OBJ) {
        mj_free(doc);
        return -1;
    }
    ver = mj_get(doc, "version");
    unchanged = mj_get(doc, "unchanged");
    rows = mj_get(doc, "settings");
    if (unchanged && unchanged->kind == MJ_BOOL && unchanged->num != 0) {
        mj_free(doc);
        return 1;
    }
    if (rows && rows->kind == MJ_ARR && (l.s = calloc(rows->n + 1, sizeof *l.s)) != NULL) {
        rc = 0;
        for (size_t i = 0; i < rows->n && rc == 0; i++) {
            rc = rows->kids[i]->kind == MJ_OBJ ? pnl_row(rows->kids[i], &l.s[i]) : -1;
            l.n = i + 1;
        }
        l.version = ver && ver->kind == MJ_NUM ? (long long)ver->num : -1;
    }
    mj_free(doc);
    if (rc != 0) {
        tui_settings_free(&l);
        return -1;
    }
    tui_settings_free(out);
    *out = l;
    return 0;
}

const tui_setting *tui_settings_get(const tui_settings *l, const char *id) {
    for (size_t i = 0; id && i < l->n; i++) {
        if (strcmp(l->s[i].id, id) == 0) {
            return &l->s[i];
        }
    }
    return NULL;
}

static int pnl_is(const tui_setting *s, const char *kind) { return strcmp(s->kind, kind) == 0; }

void tui_setting_shown(const tui_setting *s, char *out, size_t cap) {
    if (!s->value[0]) {
        (void)snprintf(out, cap, "%s", s->def_label);
        return;
    }
    for (size_t i = 0; i < s->nvalues; i++) {
        if (strcmp(s->values[i], s->value) == 0) {
            (void)snprintf(out, cap, "%s", s->labels[i]);
            return;
        }
    }
    if (pnl_is(s, "number") && s->unit) {
        (void)snprintf(out, cap, "%s %s", s->value, s->unit);
        return;
    }
    (void)snprintf(out, cap, "%s", s->value);
}

/* Changed from the default: shown in normal text, the rest dim. */
static int pnl_changed(const tui_setting *s) {
    if (pnl_is(s, "picker") && !s->unit) { /* scopedModels: patterns kept elsewhere */
        return s->value[0] != '\0';
    }
    return s->stored && s->valid && strcmp(s->stored, s->def) != 0;
}

/* ---- the rows for the filter ------------------------------------------------- */

typedef struct {
    int heading;
    size_t row; /* the setting, or the first of the heading's group */
} pnl_item;

static int pnl_has(const char *hay, const char *needle, int at_start) {
    size_t n = strlen(needle);
    for (const char *h = hay; *h; h++) {
        size_t i = 0;
        while (i < n && h[i] && tolower((unsigned char)h[i]) == tolower((unsigned char)needle[i])) {
            i++;
        }
        if (i == n) {
            return 1;
        }
        if (at_start) {
            return 0;
        }
    }
    return n == 0;
}

/* The filter's class for row s: 0 the name starts with it, 1 the name or id has it, 2 the description
 * does, -1 none. */
static int pnl_rank(const tui_setting *s, const char *f) {
    if (pnl_has(s->name, f, 1)) {
        return 0;
    }
    if (pnl_has(s->name, f, 0) || pnl_has(s->id, f, 0)) {
        return 1;
    }
    return pnl_has(s->description, f, 0) ? 2 : -1;
}

/* The list's rows into OUT (room for 2 * l->n): how many. */
static size_t pnl_items(const tui_panel *p, const tui_settings *l, pnl_item *out) {
    size_t n = 0;
    const char *f = p->filter;
    f += strspn(f, " ");
    if (!*f) {
        for (size_t i = 0; i < l->n; i++) {
            if (i == 0 || strcmp(l->s[i].group, l->s[i - 1].group) != 0) {
                out[n++] = (pnl_item){1, i};
            }
            out[n++] = (pnl_item){0, i};
        }
        return n;
    }
    for (int cls = 0; cls < 3; cls++) {
        for (size_t i = 0; i < l->n; i++) {
            if (pnl_rank(&l->s[i], f) == cls) {
                out[n++] = (pnl_item){0, i};
            }
        }
    }
    return n;
}

size_t tui_panel_list_len(const tui_panel *p, const tui_settings *l) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n = it ? pnl_items(p, l, it) : 0;
    free(it);
    return n;
}

/* The selected item's index (a setting's), or -1 when the list has none. */
static long pnl_sel(const tui_panel *p, const tui_settings *l, const pnl_item *it, size_t n) {
    long first = -1;
    for (size_t i = 0; i < n; i++) {
        if (it[i].heading) {
            continue;
        }
        if (first < 0) {
            first = (long)i;
        }
        if (strcmp(l->s[it[i].row].id, p->sel) == 0) {
            return (long)i;
        }
    }
    return first;
}

static void pnl_set_sel(tui_panel *p, const tui_settings *l, const pnl_item *it, long i) {
    if (i >= 0) {
        (void)snprintf(p->sel, sizeof p->sel, "%s", l->s[it[i].row].id);
    }
}

/* Selects the filter's best match. */
static void pnl_best(tui_panel *p, const tui_settings *l) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n = it ? pnl_items(p, l, it) : 0;
    long first = -1;
    for (size_t i = 0; i < n && first < 0; i++) {
        first = it[i].heading ? -1 : (long)i;
    }
    p->top = 0;
    if (first >= 0) { /* with no match the last one stays, for when the filter goes */
        pnl_set_sel(p, l, it, first);
    }
    free(it);
}

void tui_panel_select(tui_panel *p, const tui_settings *l, const char *id) {
    if (tui_settings_get(l, id)) {
        (void)snprintf(p->sel, sizeof p->sel, "%s", id);
        p->field = 0;
    }
}

/* ---- lines ------------------------------------------------------------------------ */

typedef struct {
    char b[4096];
    size_t n;
} pnl_buf;

static void pb_add(pnl_buf *b, const char *s, size_t n) {
    if (b->n + n >= sizeof b->b) {
        n = sizeof b->b - 1 - b->n;
    }
    memcpy(b->b + b->n, s, n);
    b->n += n;
    b->b[b->n] = '\0';
}

static void pb_str(pnl_buf *b, const char *s) { pb_add(b, s, strlen(s)); }

static void pb_spaces(pnl_buf *b, size_t n) {
    while (n-- > 0) {
        pb_add(b, " ", 1);
    }
}

static void pb_rule(pnl_buf *b, size_t n) {
    while (n-- > 0) {
        pb_str(b, "\xe2\x94\x80");
    }
}

/* S cut to COLS columns, with "…" when cut; its width in *w. */
static void pb_fit(pnl_buf *b, const char *s, size_t cols, size_t *w) {
    size_t len = strlen(s), full = tui_width(s, len), take;
    if (full <= cols) {
        pb_add(b, s, len);
        *w = full;
        return;
    }
    if (cols == 0) {
        *w = 0;
        return;
    }
    take = tui_fit(s, len, cols - 1);
    pb_add(b, s, take);
    pb_str(b, PNL_ELLIPSIS);
    *w = tui_width(s, take) + 1;
}

/* A content line: TEXT in STYLE, cut to COLS. */
static int pnl_line(tui_lines *out, const char *style, const char *text, size_t cols) {
    pnl_buf b = {{0}, 0};
    size_t w;
    pb_str(&b, style);
    pb_fit(&b, text, cols, &w);
    if (*style) {
        pb_str(&b, PNL_RESET);
    }
    return tui_lines_add(out, b.b, b.n);
}

/* The list row of setting S: the mark, the name, the value. */
static int pnl_setting_line(tui_lines *out, const tui_setting *s, int sel, size_t cols) {
    pnl_buf b = {{0}, 0};
    char shown[1200];
    size_t name_w = cols >= 48 ? 27 : cols * 55 / 100 > 4 ? cols * 55 / 100 - 2 : 2, w, used;
    const char *base = sel ? tui_fg(TUI_T_ACCENT) : "";
    if (cols < 4) {
        return tui_lines_add(out, "", 0);
    }
    pb_str(&b, base);
    pb_str(&b, sel ? PNL_ARROW " " : "  ");
    pb_fit(&b, s->name, name_w - 1, &w);
    pb_spaces(&b, name_w - w);
    used = 2 + name_w;
    if (!s->valid) {
        (void)snprintf(shown, sizeof shown, "not valid, using the default");
        pb_str(&b, tui_fg(TUI_T_ERROR));
    } else {
        tui_setting_shown(s, shown, sizeof shown);
        if (!sel) {
            pb_str(&b, pnl_changed(s) ? tui_fg(TUI_T_TEXT) : tui_fg(TUI_T_DIM));
        }
    }
    if (cols > used) {
        pb_fit(&b, shown, cols - used, &w);
    }
    pb_str(&b, PNL_RESET);
    return tui_lines_add(out, b.b, b.n);
}

/* The description area's third row, as the field shows it: "Tokens: 99" with what is wrong in red, or
 * the choices with a tick on the current one, or what Enter does; the default and when a change applies
 * at the right. The cursor's column in *ccol when a field is open. */
static int pnl_value_line(tui_lines *out, const tui_panel *p, const tui_setting *s, size_t cols, int *ccol) {
    pnl_buf left = {{0}, 0}, b = {{0}, 0};
    char right[400], shown[1200], lab[40];
    size_t lw = 0, rw;
    const char *applies = strcmp(s->applies, "now") == 0 ? "applies now" : s->applies;
    if (s->def[0] || !s->def_label[0]) {
        const char *d = s->def;
        for (size_t i = 0; i < s->nvalues; i++) {
            d = strcmp(s->values[i], s->def) == 0 ? s->labels[i] : d;
        }
        (void)snprintf(shown, sizeof shown, "%s%s%s", d, pnl_is(s, "number") && s->unit ? " " : "",
                       pnl_is(s, "number") && s->unit ? s->unit : "");
    } else {
        (void)snprintf(shown, sizeof shown, "%s", s->def_label);
    }
    (void)snprintf(right, sizeof right, "default %s" PNL_DOT "%s", shown[0] ? shown : "none", applies);
    rw = tui_width(right, strlen(right));
    if (p->field) {
        size_t avail, cw, start = 0, tw;
        const char *u = pnl_is(s, "number") && s->unit ? s->unit : "Value";
        (void)snprintf(lab, sizeof lab, "  %c%s: ", toupper((unsigned char)u[0]), u + 1);
        pb_str(&left, lab);
        lw = tui_width(lab, strlen(lab));
        avail = cols > lw + 1 ? cols - lw - 1 : 1;
        /* the text from where the cursor stays in view */
        while (start < p->cur && tui_width(p->text + start, p->cur - start) >= avail) {
            start++;
            while (start < p->cur && ((unsigned char)p->text[start] & 0xC0) == 0x80) {
                start++;
            }
        }
        cw = tui_width(p->text + start, p->cur - start);
        tw = tui_fit(p->text + start, strlen(p->text + start), avail);
        pb_add(&left, p->text + start, tw);
        *ccol = (int)(lw + cw);
        lw += tui_width(p->text + start, tw);
        if (pnl_is(s, "number") && p->text[0]) {
            char *end = NULL;
            long long v;
            errno = 0;
            v = strtoll(p->text, &end, 10);
            if (errno || !end || *end || v < s->min || v > s->max) {
                char why[120];
                if (s->max >= 1000000000LL) {
                    (void)snprintf(why, sizeof why, "   at least %lld", s->min);
                } else {
                    (void)snprintf(why, sizeof why, "   from %lld to %lld", s->min, s->max);
                }
                pb_str(&left, tui_fg(TUI_T_ERROR));
                pb_str(&left, why);
                pb_str(&left, PNL_RESET);
                lw += strlen(why);
            }
        }
    } else if (s->nvalues) {
        for (size_t i = 0; i < s->nvalues; i++) {
            int on = strcmp(s->values[i], s->value) == 0;
            size_t add = 3 + (on ? 2 : 0) + tui_width(s->labels[i], strlen(s->labels[i]));
            if (lw + add > cols) {
                break;
            }
            pb_str(&left, "   ");
            if (on) {
                pb_str(&left, tui_fg(TUI_T_ACCENT));
                pb_str(&left, PNL_TICK " ");
            }
            pb_str(&left, s->labels[i]);
            if (on) {
                pb_str(&left, PNL_RESET);
            }
            lw += add;
        }
    } else {
        const char *what = pnl_is(s, "picker") ? "  enter: choose" : "  enter: type a new value";
        pb_str(&left, tui_fg(TUI_T_DIM));
        pb_str(&left, what);
        pb_str(&left, PNL_RESET);
        lw = strlen(what);
    }
    pb_add(&b, left.b, left.n);
    if (lw + 3 + rw <= cols) {
        pb_spaces(&b, cols - lw - rw);
        pb_str(&b, tui_fg(TUI_T_DIM));
        pb_str(&b, right);
        pb_str(&b, PNL_RESET);
    }
    return tui_lines_add(out, b.b, b.n);
}

/* The description's rows: two wrapped (the second cut with "…"), or one and the note. */
static int pnl_desc(tui_lines *out, const tui_panel *p, const tui_setting *s, size_t cols) {
    tui_lines w = {NULL, 0, 0};
    int rc = tui_wrap(s->description, strlen(s->description), cols ? cols : 1, &w);
    size_t keep = p->note[0] ? 1 : 2;
    for (size_t i = 0; rc == 0 && i < keep; i++) {
        if (i < w.n && i + 1 == keep && w.n > keep) {
            char cut[1200];
            (void)snprintf(cut, sizeof cut, "%s %s", w.lines[i], w.lines[i + 1]);
            rc = pnl_line(out, "", cut, cols);
        } else {
            rc = pnl_line(out, "", i < w.n ? w.lines[i] : "", cols);
        }
    }
    if (rc == 0 && p->note[0]) {
        rc = pnl_line(out, p->note_err ? tui_fg(TUI_T_ERROR) : tui_fg(TUI_T_WARNING), p->note, cols);
    }
    tui_lines_clear(&w);
    return rc;
}

static const char *pnl_hints(const tui_panel *p, const tui_setting *s, char *buf, size_t cap) {
    if (p->field && s) {
        char shown[1100];
        tui_setting_shown(s, shown, sizeof shown);
        (void)snprintf(buf, cap, "enter: save" PNL_DOT "^R: default" PNL_DOT "esc: keep %s", shown);
        return buf;
    }
    if (p->filter[0]) {
        return "type to filter" PNL_DOT "\xe2\x86\x91\xe2\x86\x93 move" PNL_DOT "esc: clear the filter";
    }
    return "\xe2\x86\x91\xe2\x86\x93 move" PNL_DOT "\xe2\x86\x90\xe2\x86\x92 enter: change" PNL_DOT "^R: default" PNL_DOT
           "esc: close";
}

void tui_panel_scroll(size_t *top, size_t n, long sel, size_t list, size_t *first, size_t *k, int *up, int *down) {
    size_t f = *top, at = sel >= 0 ? (size_t)sel : 0;
    *up = *down = 0;
    if (n <= list) {
        *first = *top = 0;
        *k = n;
        return;
    }
    if (list < 3) { /* no room to say how many more */
        f = at < f ? at : at >= f + list ? at + 1 - list : f;
        *first = *top = f;
        *k = list;
        return;
    }
    if (f >= n) {
        f = n - 1;
    }
    for (int iter = 0; iter < 8; iter++) {
        size_t kk, margin, lo, hi;
        *up = f > 0;
        kk = list - (size_t)*up;
        *down = f + kk < n;
        kk -= (size_t)*down;
        *k = kk;
        if (sel < 0) {
            break;
        }
        margin = kk >= 3 ? 1 : 0;
        lo = at >= margin ? at - margin : 0;
        hi = at + margin < n ? at + margin : at;
        if (lo < f) {
            f = lo;
        } else if (hi >= f + kk) {
            f = hi + 1 - kk;
        } else {
            break;
        }
    }
    *first = *top = f;
}

static void pnl_window(tui_panel *p, size_t n, long sel, size_t list, size_t *first, size_t *k, int *up, int *down) {
    tui_panel_scroll(&p->top, n, sel, list, first, k, up, down);
}

/* The content lines (no border): the filter, the list, the description's three rows. The filter's
 * cursor column in *fcol, the field's in *vcol. */
static int pnl_content(tui_panel *p, const tui_settings *l, size_t cols, size_t list, tui_lines *out, int *fcol,
                       int *vcol) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n, first, k;
    long sel;
    int up, down, rc = 0;
    const tui_setting *s;
    char line[1200];
    if (!it) {
        return -1;
    }
    n = pnl_items(p, l, it);
    sel = pnl_sel(p, l, it, n);
    pnl_set_sel(p, l, it, sel);
    s = sel >= 0 ? &l->s[it[sel].row] : NULL;
    p->page = list;
    /* the filter */
    if (p->filter[0]) {
        (void)snprintf(line, sizeof line, "> %s", p->filter);
        rc |= pnl_line(out, "", line, cols);
        *fcol = (int)tui_width(line, strlen(line));
    } else {
        pnl_buf b = {{0}, 0};
        size_t w;
        pb_str(&b, "> ");
        pb_str(&b, tui_fg(TUI_T_DIM));
        pb_fit(&b, "type to filter", cols > 2 ? cols - 2 : 0, &w);
        pb_str(&b, PNL_RESET);
        rc |= tui_lines_add(out, b.b, b.n);
        *fcol = 2;
    }
    if (*fcol >= (int)cols) {
        *fcol = cols ? (int)cols - 1 : 0;
    }
    /* the list */
    pnl_window(p, n, sel, list, &first, &k, &up, &down);
    if (n == 0) {
        size_t shown = 0;
        if (list > 1) {
            rc |= tui_lines_add(out, "", 0);
            shown++;
        }
        (void)snprintf(line, sizeof line, "  No setting matches \"%s\".", p->filter);
        rc |= pnl_line(out, "", line, cols);
        shown++;
        if (shown < list) {
            (void)snprintf(line, sizeof line, "  pic settings lists every key, these %zu and the rest.", l->n);
            rc |= pnl_line(out, tui_fg(TUI_T_DIM), line, cols);
            shown++;
        }
        for (; shown < list; shown++) {
            rc |= tui_lines_add(out, "", 0);
        }
    } else {
        size_t shown = 0;
        if (up) {
            (void)snprintf(line, sizeof line, "   \xe2\x86\x91 %zu more", first);
            rc |= pnl_line(out, tui_fg(TUI_T_DIM), line, cols);
            shown++;
        }
        for (size_t i = first; i < first + k && i < n; i++, shown++) {
            if (it[i].heading) {
                pnl_buf b = {{0}, 0};
                size_t w;
                pb_str(&b, PNL_BOLD);
                pb_fit(&b, l->s[it[i].row].group, cols, &w);
                pb_str(&b, PNL_RESET);
                rc |= tui_lines_add(out, b.b, b.n);
            } else {
                rc |= pnl_setting_line(out, &l->s[it[i].row], (long)i == sel, cols);
            }
        }
        if (down) {
            (void)snprintf(line, sizeof line, "   \xe2\x86\x93 %zu more", n - first - k);
            rc |= pnl_line(out, tui_fg(TUI_T_DIM), line, cols);
            shown++;
        }
        for (; shown < list; shown++) {
            rc |= tui_lines_add(out, "", 0);
        }
    }
    /* the description */
    if (s) {
        rc |= pnl_desc(out, p, s, cols);
        rc |= pnl_value_line(out, p, s, cols, vcol);
    } else {
        for (int i = 0; i < 3; i++) {
            rc |= tui_lines_add(out, "", 0);
        }
    }
    free(it);
    return rc ? -1 : 0;
}

/* "9 of 36": the selected setting's place in the list, of all of them. */
static void pnl_count(const tui_panel *p, const tui_settings *l, char *out, size_t cap) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n = it ? pnl_items(p, l, it) : 0, at = 0;
    long sel = it ? pnl_sel(p, l, it, n) : -1;
    for (long i = 0; i <= sel; i++) {
        at += !it[i].heading;
    }
    (void)snprintf(out, cap, "%zu of %zu", at, l->n);
    free(it);
}

int tui_panel_frame(int form, const char *title, const char *count, const tui_lines *c, size_t sep, const char *hints,
                    size_t width, tui_lines *out) {
    size_t inner = width - 2, cw = width - 4, w, tw = tui_width(title, strlen(title));
    const char *border = tui_fg(TUI_T_BORDER);
    pnl_buf b = {{0}, 0};
    int rc = 0;
    if (form == TUI_PANEL_DOCK) {
        pb_str(&b, PNL_BOLD);
        pb_str(&b, title);
        pb_str(&b, PNL_RESET "  ");
        pb_str(&b, tui_fg(TUI_T_DIM));
        pb_fit(&b, count, width > tw + 2 ? width - tw - 2 : 0, &w);
        pb_str(&b, PNL_RESET);
        rc |= tui_lines_add(out, b.b, b.n);
        for (size_t i = 0; i < c->n; i++) {
            b.n = 0;
            pb_str(&b, i == 0 ? "" : " "); /* the filter at the left edge, as Pi's lists have it */
            pb_str(&b, c->lines[i]);
            rc |= tui_lines_add(out, b.b, b.n);
        }
        if (hints && *hints) {
            b.n = 0;
            pb_str(&b, " ");
            pb_str(&b, tui_fg(TUI_T_DIM));
            pb_fit(&b, hints, width > 1 ? width - 1 : 1, &w);
            pb_str(&b, PNL_RESET);
            rc |= tui_lines_add(out, b.b, b.n);
        }
        return rc ? -1 : 0;
    }
    /* top: ┌─ Settings ──── 9 of 36 ─┐ */
    pb_str(&b, border);
    pb_str(&b, "\xe2\x94\x8c\xe2\x94\x80 ");
    pb_str(&b, PNL_RESET PNL_BOLD);
    pb_str(&b, title);
    pb_str(&b, PNL_RESET);
    pb_str(&b, border);
    pb_str(&b, " ");
    {
        size_t cwid = strlen(count);
        if (inner >= tw + 7 + cwid) { /* "┌─ Settings " RULE " 9 of 36 ─┐" */
            pb_rule(&b, inner - tw - 6 - cwid);
            pb_str(&b, " ");
            pb_str(&b, PNL_RESET);
            pb_str(&b, tui_fg(TUI_T_DIM));
            pb_str(&b, count);
            pb_str(&b, PNL_RESET);
            pb_str(&b, border);
            pb_str(&b, " \xe2\x94\x80");
        } else if (inner > tw + 3) {
            pb_rule(&b, inner - tw - 3);
        }
    }
    pb_str(&b, "\xe2\x94\x90" PNL_RESET);
    rc |= tui_lines_add(out, b.b, b.n);
    for (size_t i = 0; i < c->n; i++) {
        size_t lw = tui_width(c->lines[i], strlen(c->lines[i]));
        if (sep && i == sep) { /* ├────┤ above the description */
            b.n = 0;
            pb_str(&b, border);
            pb_str(&b, "\xe2\x94\x9c");
            pb_rule(&b, inner);
            pb_str(&b, "\xe2\x94\xa4" PNL_RESET);
            rc |= tui_lines_add(out, b.b, b.n);
        }
        b.n = 0;
        pb_str(&b, border);
        pb_str(&b, "\xe2\x94\x82" PNL_RESET " ");
        pb_str(&b, c->lines[i]);
        pb_str(&b, PNL_RESET);
        pb_spaces(&b, lw < cw ? cw - lw : 0);
        pb_str(&b, " ");
        pb_str(&b, border);
        pb_str(&b, "\xe2\x94\x82" PNL_RESET);
        rc |= tui_lines_add(out, b.b, b.n);
    }
    /* bottom: └─ keys ───┘ */
    b.n = 0;
    pb_str(&b, border);
    if (hints && *hints) {
        pb_str(&b, "\xe2\x94\x94\xe2\x94\x80 " PNL_RESET);
        pb_str(&b, tui_fg(TUI_T_DIM));
        pb_fit(&b, hints, inner > 4 ? inner - 4 : 0, &w);
        pb_str(&b, PNL_RESET);
        pb_str(&b, border);
        pb_str(&b, " ");
        pb_rule(&b, inner > 3 + w ? inner - 3 - w : 0);
    } else {
        pb_str(&b, "\xe2\x94\x94");
        pb_rule(&b, inner);
    }
    pb_str(&b, "\xe2\x94\x98" PNL_RESET);
    rc |= tui_lines_add(out, b.b, b.n);
    return rc ? -1 : 0;
}

static int pnl_box(tui_panel *p, const tui_settings *l, size_t width, size_t list, tui_lines *out, int *crow,
                   int *ccol) {
    tui_lines c = {NULL, 0, 0};
    size_t base = out->n;
    int fcol = 0, vcol = -1, rc;
    char count[40], hints[1300];
    rc = pnl_content(p, l, width - 4, list, &c, &fcol, &vcol);
    pnl_count(p, l, count, sizeof count);
    rc |= tui_panel_frame(TUI_PANEL_BOX, "Settings", count, &c, 1 + list,
                          pnl_hints(p, tui_settings_get(l, p->sel), hints, sizeof hints), width, out);
    if (p->field && vcol >= 0) {
        *crow = (int)(base + 1 + 1 + list + 1 + 2);
        *ccol = 2 + vcol;
    } else {
        *crow = (int)(base + 1);
        *ccol = 2 + fcol;
    }
    tui_lines_clear(&c);
    return rc ? -1 : 0;
}

static int pnl_dock(tui_panel *p, const tui_settings *l, size_t width, size_t list, tui_lines *out, int *crow,
                    int *ccol) {
    tui_lines c = {NULL, 0, 0};
    size_t base = out->n;
    int fcol = 0, vcol = -1, rc;
    char count[40], hints[1300];
    rc = pnl_content(p, l, width > 1 ? width - 1 : 1, list, &c, &fcol, &vcol);
    pnl_count(p, l, count, sizeof count);
    rc |= tui_panel_frame(TUI_PANEL_DOCK, "Settings", count, &c, 0,
                          pnl_hints(p, tui_settings_get(l, p->sel), hints, sizeof hints), width, out);
    if (p->field && vcol >= 0) {
        *crow = (int)(base + 1 + 1 + list + 2);
        *ccol = 1 + vcol;
    } else {
        *crow = (int)(base + 1);
        *ccol = fcol;
    }
    tui_lines_clear(&c);
    return rc ? -1 : 0;
}

static int pnl_one(tui_panel *p, const tui_settings *l, size_t width, tui_lines *out, int *crow, int *ccol) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n, at = 0, w, rows = out->n;
    long sel;
    pnl_buf b = {{0}, 0};
    char head[1300], shown[1200];
    const tui_setting *s;
    int rc = 0;
    if (!it) {
        return -1;
    }
    n = pnl_items(p, l, it);
    sel = pnl_sel(p, l, it, n);
    pnl_set_sel(p, l, it, sel);
    for (long i = 0; i <= sel; i++) {
        at += !it[i].heading;
    }
    s = sel >= 0 ? &l->s[it[sel].row] : NULL;
    if (!s) {
        (void)snprintf(head, sizeof head, "Settings 0/%zu: no match for \"%s\"", l->n, p->filter);
        rc |= pnl_line(out, "", head, width);
    } else if (p->field) {
        size_t tw;
        (void)snprintf(head, sizeof head, "%s: ", s->name);
        pb_fit(&b, head, width > 8 ? width - 8 : width, &w);
        tw = tui_fit(p->text, strlen(p->text), width > w + 1 ? width - w - 1 : 0);
        pb_add(&b, p->text, tw);
        *crow = (int)rows;
        *ccol = (int)(w + tui_width(p->text, p->cur < tw ? p->cur : tw));
        rc |= tui_lines_add(out, b.b, b.n);
    } else {
        tui_setting_shown(s, shown, sizeof shown);
        (void)snprintf(head, sizeof head, "Settings %zu/%zu %s: %s", at, l->n, s->name, shown);
        pb_str(&b, PNL_BOLD);
        pb_fit(&b, head, width, &w);
        pb_str(&b, PNL_RESET);
        rc |= tui_lines_add(out, b.b, b.n);
        *crow = -1;
    }
    rc |= pnl_line(out, tui_fg(TUI_T_DIM),
                   p->field ? " enter: save \xc2\xb7 esc: keep" : " \xe2\x86\x91\xe2\x86\x93 \xe2\x86\x90\xe2\x86\x92 esc \xc2\xb7 widen for more",
                   width);
    free(it);
    return rc ? -1 : 0;
}

int tui_panel_lines(tui_panel *p, const tui_settings *l, int form, size_t width, size_t list, tui_lines *out, int *crow,
                    int *ccol) {
    *crow = -1;
    *ccol = 0;
    p->form = form == TUI_PANEL_BOX && width >= 24 ? TUI_PANEL_BOX : form == TUI_PANEL_DOCK && width >= 12 ? TUI_PANEL_DOCK
                                                                                                          : TUI_PANEL_LINE;
    if (form == TUI_PANEL_BOX && width >= 24) {
        return pnl_box(p, l, width, list ? list : 1, out, crow, ccol);
    }
    if (form == TUI_PANEL_DOCK && width >= 12) {
        return pnl_dock(p, l, width, list ? list : 1, out, crow, ccol);
    }
    return pnl_one(p, l, width ? width : 1, out, crow, ccol);
}

/* The box and the dock have the list from their third line: the title (or top border) and the filter
 * above it. */
#define PNL_LIST_LINE 2

int tui_panel_click(tui_panel *p, const tui_settings *l, size_t line) {
    pnl_item *it;
    size_t n, first, k, at;
    long sel;
    int up, down, done = 0;
    if (p->form == TUI_PANEL_LINE || line < PNL_LIST_LINE || line >= PNL_LIST_LINE + p->page) {
        return 0;
    }
    if (!(it = calloc(2 * l->n + 1, sizeof *it))) {
        return 0;
    }
    n = pnl_items(p, l, it);
    sel = pnl_sel(p, l, it, n);
    pnl_window(p, n, sel, p->page, &first, &k, &up, &down); /* as last drawn */
    at = line - PNL_LIST_LINE;
    if (!(up && at == 0) && at >= (size_t)up && at - (size_t)up < k) {
        size_t i = first + at - (size_t)up;
        if (i < n && !it[i].heading) {
            pnl_set_sel(p, l, it, (long)i);
            p->field = 0;
            done = 1;
        }
    }
    free(it);
    return done;
}

/* ---- keys --------------------------------------------------------------------------- */

/* Text typed into the filter or the field at its cursor: control characters dropped, a number's digits
 * only. */
static void pnl_insert(tui_panel *p, const tui_setting *s, const char *t, size_t n) {
    int digits = p->field && s && pnl_is(s, "number");
    char *buf = p->field ? p->text : p->filter;
    size_t cap = p->field ? sizeof p->text : sizeof p->filter, len = strlen(buf), at = p->field ? p->cur : len;
    for (size_t i = 0; i < n; i++) {
        unsigned char c = (unsigned char)t[i];
        size_t need = 1;
        if (c < 0x20 || c == 0x7f) {
            continue;
        }
        if (digits && !(isdigit(c) || (c == '-' && at == 0 && s->min < 0))) {
            continue;
        }
        if (c >= 0x80) { /* a whole UTF-8 character or nothing */
            need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
            if (i + need > n) {
                break;
            }
        }
        if (len + need >= cap) {
            break;
        }
        memmove(buf + at + need, buf + at, len - at + 1);
        memcpy(buf + at, t + i, need);
        at += need;
        len += need;
        i += need - 1;
    }
    if (p->field) {
        p->cur = at;
    }
}

static size_t pnl_back(const char *s, size_t at) {
    if (at == 0) {
        return 0;
    }
    at--;
    while (at > 0 && ((unsigned char)s[at] & 0xC0) == 0x80) {
        at--;
    }
    return at;
}

static size_t pnl_fwd(const char *s, size_t at) {
    if (!s[at]) {
        return at;
    }
    at++;
    while (s[at] && ((unsigned char)s[at] & 0xC0) == 0x80) {
        at++;
    }
    return at;
}

/* Moves the selection by DIR rows (wrapping when WRAP), or to the first (PNL_FIRST) or last (PNL_LAST). */
static void pnl_move(tui_panel *p, const tui_settings *l, long dir, int wrap) {
    pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
    size_t n, nrows = 0, *rows;
    long sel, at = 0;
    if (!it) {
        return;
    }
    n = pnl_items(p, l, it);
    rows = calloc(n + 1, sizeof *rows);
    sel = pnl_sel(p, l, it, n);
    for (size_t i = 0; rows && i < n; i++) {
        if (!it[i].heading) {
            if ((long)i == sel) {
                at = (long)nrows;
            }
            rows[nrows++] = i;
        }
    }
    if (rows && nrows) {
        long to = at + dir;
        if (dir == PNL_FIRST || dir == PNL_LAST) {
            to = dir < 0 ? 0 : (long)nrows - 1;
        } else if (wrap) {
            to = ((to % (long)nrows) + (long)nrows) % (long)nrows;
        } else {
            to = to < 0 ? 0 : to >= (long)nrows ? (long)nrows - 1 : to;
        }
        pnl_set_sel(p, l, it, (long)rows[to]);
    }
    free(rows);
    free(it);
}

static void pnl_field_open(tui_panel *p, const tui_setting *s) {
    p->field = 1;
    (void)snprintf(p->text, sizeof p->text, "%s", s->valid && s->stored ? s->stored : s->value);
    p->cur = strlen(p->text);
    p->note[0] = '\0';
}

/* The next (dir 1) or previous (-1) value of a choice into act. */
static int pnl_step(const tui_setting *s, int dir, tui_panel_act *act) {
    size_t at = 0;
    if (!s->nvalues) {
        return TUI_PANEL_NONE;
    }
    while (at < s->nvalues && strcmp(s->values[at], s->value) != 0) {
        at++;
    }
    if (at == s->nvalues) {
        at = dir > 0 ? s->nvalues - 1 : 0;
    }
    at = (at + s->nvalues + (size_t)(dir > 0 ? 1 : s->nvalues - 1)) % s->nvalues;
    (void)snprintf(act->id, sizeof act->id, "%s", s->id);
    (void)snprintf(act->value, sizeof act->value, "%s", s->values[at]);
    return act->what = TUI_PANEL_SET;
}

static int pnl_ctrl(const tui_key *k, const char *base) {
    return k->kind == TUI_KEY_OTHER && (k->mods & TUI_MOD_CTRL) && strcmp(k->base, base) == 0;
}

static int pnl_field_key(tui_panel *p, const tui_setting *s, const tui_key *k, tui_panel_act *act) {
    size_t len = strlen(p->text);
    switch (k->kind) {
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        p->field = 0;
        p->note[0] = '\0';
        break;
    case TUI_KEY_ENTER:
        if (pnl_is(s, "number")) {
            char *end = NULL;
            long long v;
            errno = 0;
            v = strtoll(p->text, &end, 10);
            if (!p->text[0] || errno || !end || *end || v < s->min || v > s->max) {
                break; /* the field says what is wrong; nothing is saved */
            }
        }
        (void)snprintf(act->id, sizeof act->id, "%s", s->id);
        (void)snprintf(act->value, sizeof act->value, "%s", p->text);
        act->what = TUI_PANEL_SET;
        break;
    case TUI_KEY_CHAR: pnl_insert(p, s, k->text, strlen(k->text)); break;
    case TUI_KEY_PASTE: pnl_insert(p, s, k->paste, k->paste_len); break;
    case TUI_KEY_BACKSPACE:
        if (p->cur > 0) {
            size_t to = pnl_back(p->text, p->cur);
            memmove(p->text + to, p->text + p->cur, len - p->cur + 1);
            p->cur = to;
        }
        break;
    case TUI_KEY_DELETE:
        if (p->cur < len) {
            size_t to = pnl_fwd(p->text, p->cur);
            memmove(p->text + p->cur, p->text + to, len - to + 1);
        }
        break;
    case TUI_KEY_LEFT: p->cur = pnl_back(p->text, p->cur); break;
    case TUI_KEY_RIGHT: p->cur = pnl_fwd(p->text, p->cur); break;
    case TUI_KEY_HOME: p->cur = 0; break;
    case TUI_KEY_END: p->cur = len; break;
    case TUI_KEY_KILL_START:
        memmove(p->text, p->text + p->cur, len - p->cur + 1);
        p->cur = 0;
        break;
    case TUI_KEY_KILL_LINE: p->text[p->cur] = '\0'; break;
    case TUI_KEY_DELETE_WORD: {
        size_t to = p->cur;
        while (to > 0 && p->text[to - 1] == ' ') {
            to--;
        }
        while (to > 0 && p->text[to - 1] != ' ' && p->text[to - 1] != ',') {
            to--;
        }
        memmove(p->text + to, p->text + p->cur, len - p->cur + 1);
        p->cur = to;
        break;
    }
    default:
        if (pnl_ctrl(k, "r")) { /* the default, to save or edit */
            (void)snprintf(p->text, sizeof p->text, "%s", s->def);
            p->cur = strlen(p->text);
        }
        break;
    }
    return 0;
}

int tui_panel_key(tui_panel *p, const tui_settings *l, const tui_key *k, tui_panel_act *act) {
    const tui_setting *s;
    size_t len = strlen(p->filter);
    memset(act, 0, sizeof *act);
    act->what = TUI_PANEL_NONE;
    {
        pnl_item *it = calloc(2 * l->n + 1, sizeof *it);
        size_t n = it ? pnl_items(p, l, it) : 0;
        long sel = it ? pnl_sel(p, l, it, n) : -1;
        if (it) {
            pnl_set_sel(p, l, it, sel);
        }
        s = sel >= 0 && it ? &l->s[it[sel].row] : NULL;
        free(it);
    }
    if (p->field && s) {
        return pnl_field_key(p, s, k, act);
    }
    p->field = 0;
    switch (k->kind) {
    case TUI_KEY_UP: pnl_move(p, l, -1, 1); break;
    case TUI_KEY_DOWN: pnl_move(p, l, 1, 1); break;
    case TUI_KEY_PAGEUP: pnl_move(p, l, -(long)(p->page > 1 ? p->page - 1 : 1), 0); break;
    case TUI_KEY_PAGEDOWN: pnl_move(p, l, (long)(p->page > 1 ? p->page - 1 : 1), 0); break;
    case TUI_KEY_HOME:
    case TUI_KEY_CTRL_HOME: pnl_move(p, l, PNL_FIRST, 0); break;
    case TUI_KEY_END:
    case TUI_KEY_CTRL_END: pnl_move(p, l, PNL_LAST, 0); break;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        if (p->filter[0]) {
            p->filter[0] = '\0';
        } else {
            act->what = TUI_PANEL_CLOSE;
        }
        break;
    case TUI_KEY_RIGHT:
        if (s) {
            (void)pnl_step(s, 1, act);
        }
        break;
    case TUI_KEY_LEFT:
        if (s) {
            (void)pnl_step(s, -1, act);
        }
        break;
    case TUI_KEY_ENTER:
        if (!s) {
            break;
        }
        if (pnl_is(s, "picker")) {
            (void)snprintf(act->id, sizeof act->id, "%s", s->id);
            act->what = TUI_PANEL_PICK;
        } else if (s->nvalues) {
            (void)pnl_step(s, 1, act);
        } else {
            pnl_field_open(p, s);
        }
        break;
    case TUI_KEY_CHAR:
        if (k->text[0] == ' ' && !k->text[1] && !p->filter[0]) { /* Pi: Space changes while there is no filter */
            if (s) {
                (void)pnl_step(s, 1, act);
            }
            break;
        }
        pnl_insert(p, s, k->text, strlen(k->text));
        pnl_best(p, l);
        break;
    case TUI_KEY_PASTE:
        pnl_insert(p, s, k->paste, k->paste_len);
        pnl_best(p, l);
        break;
    case TUI_KEY_BACKSPACE:
        if (len > 0) {
            p->filter[pnl_back(p->filter, len)] = '\0';
            if (p->filter[0]) { /* the best match; with the filter gone the setting found stays selected */
                pnl_best(p, l);
            }
        }
        break;
    case TUI_KEY_KILL_START:
    case TUI_KEY_DELETE_WORD:
        p->filter[0] = '\0';
        break;
    default:
        if (pnl_ctrl(k, "r") && s) {
            (void)snprintf(act->id, sizeof act->id, "%s", s->id);
            act->what = TUI_PANEL_RESET;
        }
        break;
    }
    return 0;
}