Skip to content
pi-c Artifact [a1530f2d3b]
Login

Artifact [a1530f2d3b]

Artifact a1530f2d3b60abe951b52ccd56eb0fdc2aaf9fa54d84a6a7b79286e3d2a60187:


/* The fullscreen viewport's math and line operations; see viewport.h. */
#include "tui/viewport.h"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Pi's PAGE_SCROLL_OVERLAP (tui-alt-screen.ts). */
#define PAGE_OVERLAP 4
/* wheel-scroll.ts */
#define BURST_GAP_MS 5.0
#define GESTURE_GAP_MS 200.0
#define REFERENCE_GAP_MS 100.0
#define MAX_AUTO_LINES 6.0

#define REVERSE "\x1b[7m"
#define REVERSE_OFF "\x1b[27m"
#define RESET "\x1b[0m"

/* ---- scrolling ------------------------------------------------------------ */

void tui_scroll_init(tui_scroll *s)
{
    memset(s, 0, sizeof *s);
    s->follow = 1;
}

size_t tui_scroll_max(const tui_scroll *s)
{
    return s->content > s->height ? s->content - s->height : 0;
}

void tui_scroll_layout(tui_scroll *s, size_t content, size_t height)
{
    s->content = content;
    s->height = height;
    size_t max = tui_scroll_max(s);
    if (s->follow || s->top > max)
        s->top = max;
    if (s->top == max && !s->hold)
        s->follow = 1;
}

int tui_scroll_by(tui_scroll *s, long delta)
{
    size_t max = tui_scroll_max(s), start = s->follow ? max : s->top, next;
    if (delta < 0)
        next = (size_t)-delta >= start ? 0 : start - (size_t)-delta;
    else
        next = (size_t)delta >= max - start ? max : start + (size_t)delta;
    s->top = next;
    s->follow = next == max;
    s->hold = 0;
    return next != start;
}

void tui_scroll_to(tui_scroll *s, size_t top, int disable_follow)
{
    size_t max = tui_scroll_max(s);
    s->top = top < max ? top : max;
    s->hold = disable_follow && s->top == max;
    s->follow = s->top == max && !s->hold;
}

long tui_scroll_page(const tui_scroll *s, int dir)
{
    long n = s->height > PAGE_OVERLAP + 1 ? (long)(s->height - PAGE_OVERLAP) : 1;
    return dir < 0 ? -n : n;
}

void tui_scroll_start(tui_scroll *s)
{
    s->top = 0;
    s->follow = s->content <= s->height;
    s->hold = 0;
}

void tui_scroll_end(tui_scroll *s)
{
    s->top = tui_scroll_max(s);
    s->follow = 1;
    s->hold = 0;
}

int tui_scrollbar_geometry(const tui_scroll *s, tui_scrollbar *g)
{
    size_t h = s->height, max = tui_scroll_max(s);
    if (h == 0)
        return 0;
    if (s->content <= h) {
        g->thumb_top = 0;
        g->thumb_height = h;
        return 1;
    }
    /* round(h*h / content), at least min(2, h), at most h */
    size_t th = (h * h * 2 + s->content) / (s->content * 2), lo = h < 2 ? h : 2;
    if (th > h)
        th = h;
    if (th < lo)
        th = lo;
    size_t room = h - th, top = s->top > max ? max : s->top;
    g->thumb_height = th;
    g->thumb_top = max ? (top * room * 2 + max) / (max * 2) : 0;
    return 1;
}

int tui_scrollbar_mode(const char *setting)
{
    if (setting && strcmp(setting, "always") == 0)
        return TUI_BAR_ALWAYS;
    if (setting && strcmp(setting, "hidden") == 0)
        return TUI_BAR_HIDDEN;
    return TUI_BAR_AUTO;
}

/* ---- the wheel ------------------------------------------------------------ */

void tui_wheel_init(tui_wheel *w, int lines, int accelerate)
{
    w->lines = lines;
    w->accelerate = accelerate;
    w->last = -1;
    w->dir = 0;
    w->avg = -1;
    w->carry = 0;
}

int tui_wheel_next(tui_wheel *w, int dir, double now)
{
    if (w->lines > 0)
        return w->lines;
    if (!w->accelerate)
        return 1;
    double gap = w->last < 0 ? GESTURE_GAP_MS + 1 : now - w->last;
    int same = dir == w->dir && gap <= GESTURE_GAP_MS;
    w->last = now;
    w->dir = dir;
    if (!same) {
        w->avg = -1;
        w->carry = 0;
        return 1;
    }
    if (gap < BURST_GAP_MS)
        return 1;
    w->avg = w->avg < 0 ? gap : (w->avg + gap) / 2;
    double lines = REFERENCE_GAP_MS / w->avg;
    if (lines < 1)
        lines = 1;
    if (lines > MAX_AUTO_LINES)
        lines = MAX_AUTO_LINES;
    lines += w->carry;
    int whole = (int)lines;
    w->carry = lines - whole;
    return whole;
}

int tui_wheel_lines(const char *setting)
{
    char *end = NULL;
    long v;
    if (!setting || !*setting || strcmp(setting, "auto") == 0)
        return 0;
    v = strtol(setting, &end, 10);
    if (!end || end == setting || *end)
        return 0;
    return v < 1 ? 1 : v > 100 ? 100 : (int)v;
}

/* ---- walking a styled line ------------------------------------------------- */

/* Bytes of the escape sequence at s (s[0] is ESC): CSI up to its final byte,
 * OSC up to BEL or ESC \, else ESC and one byte. */
static size_t esc_len(const char *s, size_t n)
{
    size_t i;
    if (n < 2)
        return n;
    if (s[1] == '[') {
        for (i = 2; i < n && !((unsigned char)s[i] >= 0x40 && (unsigned char)s[i] <= 0x7e); i++) {
        }
        return i < n ? i + 1 : n;
    }
    if (s[1] == ']') {
        for (i = 2; i < n; i++) {
            if (s[i] == '\a')
                return i + 1;
            if (s[i] == 0x1b && i + 1 < n && s[i + 1] == '\\')
                return i + 2;
        }
        return n;
    }
    return 2;
}

/* The character at s: its bytes and columns. */
static size_t char_at(const char *s, size_t n, int *cols)
{
    uint32_t cp;
    size_t used = tui_utf8_decode(s, n, &cp);
    *cols = cp == '\t' ? 4 : tui_cp_width(cp);
    return used;
}

typedef struct {
    char *buf;
    size_t n, cap;
    int oom;
} sbuf;

static void sb_add(sbuf *b, const char *s, size_t n)
{
    if (b->oom)
        return;
    if (b->n + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 64;
        while (cap < b->n + n + 1)
            cap *= 2;
        char *p = realloc(b->buf, cap);
        if (!p) {
            b->oom = 1;
            return;
        }
        b->buf = p, b->cap = cap;
    }
    memcpy(b->buf + b->n, s, n);
    b->n += n;
    b->buf[b->n] = '\0';
}

static void sb_str(sbuf *b, const char *s)
{
    sb_add(b, s, strlen(s));
}

static char *sb_done(sbuf *b)
{
    if (b->oom) {
        free(b->buf);
        return NULL;
    }
    if (!b->buf)
        return strdup("");
    return b->buf;
}

char *tui_line_plain(const char *line, size_t c0, size_t c1)
{
    sbuf b = {NULL, 0, 0, 0};
    size_t n = strlen(line), i = 0, col = 0;
    while (i < n && col < c1) {
        if (line[i] == 0x1b) {
            i += esc_len(line + i, n - i);
            continue;
        }
        int w;
        size_t used = char_at(line + i, n - i, &w);
        if (col >= c0 && w >= 0) {
            if (line[i] == '\t')
                sb_add(&b, "    ", 4);
            else if ((unsigned char)line[i] >= 0x20)
                sb_add(&b, line + i, used);
        }
        col += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    return sb_done(&b);
}

char *tui_line_link_at(const char *line, size_t c)
{
    size_t n = strlen(line), i = 0, col = 0, us = 0, un = 0;
    while (i < n && col <= c) {
        if (line[i] == 0x1b) {
            size_t e = esc_len(line + i, n - i);
            if (e > 5 && memcmp(line + i + 1, "]8;", 3) == 0) {
                const char *semi = memchr(line + i + 4, ';', e - 4);
                size_t term = line[i + e - 1] == '\a' ? 1 : 2;
                us = un = 0;
                if (semi && (size_t)(semi - line) + 1 + term < i + e) {
                    us = (size_t)(semi - line) + 1;
                    un = i + e - term - us;
                }
            }
            i += e;
            continue;
        }
        int w;
        size_t used = char_at(line + i, n - i, &w);
        if (w > 0 && c < col + (size_t)w) {
            if (!un)
                return NULL;
            char *u = malloc(un + 1);
            if (u) {
                memcpy(u, line + us, un);
                u[un] = '\0';
            }
            return u;
        }
        col += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    return NULL;
}

char *tui_line_highlight(const char *line, size_t c0, size_t c1)
{
    sbuf b = {NULL, 0, 0, 0};
    size_t n = strlen(line), i = 0, col = 0;
    int on = 0;
    while (i < n) {
        if (line[i] == 0x1b) {
            size_t e = esc_len(line + i, n - i);
            sb_add(&b, line + i, e);
            if (on && e >= 3 && line[i + 1] == '[' && line[i + e - 1] == 'm')
                sb_str(&b, REVERSE); /* an SGR reset would end it */
            i += e;
            continue;
        }
        int w;
        size_t used = char_at(line + i, n - i, &w);
        if (!on && col >= c0 && col < c1 && w > 0) {
            sb_str(&b, REVERSE);
            on = 1;
        } else if (on && col >= c1 && w > 0) {
            sb_str(&b, REVERSE_OFF);
            on = 0;
        }
        sb_add(&b, line + i, used);
        col += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    if (on)
        sb_str(&b, REVERSE_OFF);
    return sb_done(&b);
}

char *tui_line_bar(const char *line, size_t cols, const char *glyph)
{
    sbuf b = {NULL, 0, 0, 0};
    size_t room = cols > 0 ? cols - 1 : 0, n = strlen(line);
    size_t fit = tui_fit(line, n, room), w = tui_width(line, fit);
    sb_add(&b, line, fit);
    sb_str(&b, RESET);
    for (; w < room; w++)
        sb_add(&b, " ", 1);
    if (cols > 0)
        sb_str(&b, glyph);
    return sb_done(&b);
}

int tui_line_layout(const char *line, size_t cols, tui_lines *out)
{
    size_t n = strlen(line), fit;
    if (cols < 1)
        cols = 1;
    if (tui_width(line, n) <= cols)
        return tui_lines_add(out, line, n);
    fit = tui_fit(line, n, cols);
    {
        char *rest = tui_line_plain(line + fit, 0, (size_t)-1);
        int blank = rest && rest[strspn(rest, " ")] == '\0';
        free(rest);
        if (blank) {
            /* Keep the escapes after the cut (a closing reset, a link end). */
            sbuf b = {NULL, 0, 0, 0};
            sb_add(&b, line, fit);
            for (size_t i = fit; i < n;) {
                if (line[i] == 0x1b) {
                    size_t e = esc_len(line + i, n - i);
                    sb_add(&b, line + i, e);
                    i += e;
                } else {
                    i++;
                }
            }
            char *s = sb_done(&b);
            int rc = s ? tui_lines_add(out, s, strlen(s)) : -1;
            free(s);
            return rc;
        }
    }
    return tui_wrap(line, n, cols, out);
}

/* ---- selection ---------------------------------------------------------- */

static int before(tui_point a, tui_point b)
{
    return a.line < b.line || (a.line == b.line && a.col < b.col);
}

int tui_selection_bounds(const tui_selection *s, tui_point *start, tui_point *end)
{
    if (!s->on || (s->anchor.line == s->focus.line && s->anchor.col == s->focus.col))
        return 0;
    if (before(s->anchor, s->focus)) {
        *start = s->anchor;
        *end = s->focus;
    } else {
        *start = s->focus;
        *end = s->anchor;
    }
    return 1;
}

int tui_selection_cols(const tui_selection *s, size_t line, size_t width, size_t *c0, size_t *c1)
{
    tui_point a, b;
    size_t lo = 0, hi = width;
    if (!tui_selection_bounds(s, &a, &b) || line < a.line || line > b.line)
        return 0;
    if (line == a.line)
        lo = a.col < width ? a.col : width;
    if (line == b.line)
        hi = b.col + 1 < width ? b.col + 1 : width;
    if (lo >= hi)
        return 0;
    *c0 = lo;
    *c1 = hi;
    return 1;
}

char *tui_selection_text(const tui_selection *s, const char *(*line_at)(void *ctx, size_t i), void *ctx)
{
    tui_point a, b;
    sbuf out = {NULL, 0, 0, 0};
    if (!tui_selection_bounds(s, &a, &b))
        return NULL;
    for (size_t l = a.line; l <= b.line; l++) {
        const char *line = line_at(ctx, l);
        size_t w = tui_width(line, strlen(line)), c0, c1;
        if (l > a.line)
            sb_add(&out, "\n", 1);
        if (tui_selection_cols(s, l, w, &c0, &c1)) {
            char *p = tui_line_plain(line, c0, c1);
            if (!p) {
                free(out.buf);
                return NULL;
            }
            size_t len = strlen(p);
            while (len > 0 && p[len - 1] == ' ')
                len--;
            sb_add(&out, p, len);
            free(p);
        }
    }
    char *text = sb_done(&out);
    if (text && !*text) {
        free(text);
        return NULL;
    }
    return text;
}

/* ---- transcript search ---------------------------------------------------- */

/* Simple case folding: ASCII, Latin-1, Latin Extended-A, Greek and Cyrillic. */
static uint32_t fold(uint32_t c)
{
    if (c < 0x80)
        return c >= 'A' && c <= 'Z' ? c + 32 : c;
    if ((c >= 0xC0 && c <= 0xDE && c != 0xD7) || (c >= 0x391 && c <= 0x3A9 && c != 0x3A2) || (c >= 0x410 && c <= 0x42F))
        return c + 32;
    if (c >= 0x400 && c <= 0x40F)
        return c + 80;
    if ((c >= 0x100 && c <= 0x137) || (c >= 0x14A && c <= 0x177))
        return c & 1 ? c : c + 1;
    if ((c >= 0x139 && c <= 0x148) || (c >= 0x179 && c <= 0x17E))
        return c & 1 ? c + 1 : c;
    return c == 0x178 ? 0xFF : c;
}

static int vp_is_space(uint32_t c)
{
    return c == ' ' || c == '\t' || c == 0xA0 || c == 0x3000 || (c >= 0x2000 && c <= 0x200A);
}

#define SEP_ROW UINT32_MAX

/* The text being searched: one code point per entry, folded, with where it is. */
typedef struct {
    uint32_t *cp, *row, *c0, *c1;
    size_t n, cap;
} corpus;

static int corpus_add(corpus *c, uint32_t cp, uint32_t row, uint32_t c0, uint32_t c1)
{
    if (c->n == c->cap) {
        size_t cap = c->cap ? c->cap * 2 : 256;
        uint32_t *p[4];
        uint32_t **f[4] = {&c->cp, &c->row, &c->c0, &c->c1};
        for (int i = 0; i < 4; i++) {
            p[i] = realloc(*f[i], cap * sizeof **f[i]);
            if (!p[i])
                return -1;
            *f[i] = p[i];
        }
        c->cap = cap;
    }
    c->cp[c->n] = cp;
    c->row[c->n] = row;
    c->c0[c->n] = c0;
    c->c1[c->n] = c1;
    c->n++;
    return 0;
}

static void corpus_free(corpus *c)
{
    free(c->cp);
    free(c->row);
    free(c->c0);
    free(c->c1);
}

static int corpus_build(corpus *c, size_t nlines, const char *(*line_at)(void *, size_t), void *ctx)
{
    int pending = 0;
    for (size_t row = 0; row < nlines; row++) {
        const char *line = line_at(ctx, row);
        size_t n = strlen(line), i = 0, col = 0;
        while (i < n) {
            uint32_t cp;
            size_t used;
            int w;
            if (line[i] == 0x1b) {
                i += esc_len(line + i, n - i);
                continue;
            }
            used = tui_utf8_decode(line + i, n - i, &cp);
            i += used;
            if (cp != '\t' && cp < 0x20)
                continue;
            w = cp == '\t' ? 4 : tui_cp_width(cp);
            if (vp_is_space(cp)) {
                if (c->n > 0)
                    pending = 1;
                col += (size_t)w;
                continue;
            }
            if (pending && corpus_add(c, ' ', SEP_ROW, 0, 0) != 0)
                return -1;
            pending = 0;
            if (corpus_add(c, fold(cp), (uint32_t)row, (uint32_t)col, (uint32_t)(col + (size_t)(w > 0 ? w : 0))) != 0)
                return -1;
            col += (size_t)(w > 0 ? w : 0);
        }
        if (c->n > 0)
            pending = 1;
    }
    return 0;
}

/* The query as folded code points with whitespace runs collapsed and trimmed. */
static size_t query_cps(const char *q, uint32_t **out)
{
    size_t n = strlen(q), i = 0, m = 0;
    int pending = 0;
    uint32_t *v = malloc((n + 1) * sizeof *v);
    if (!v)
        return (size_t)-1;
    while (i < n) {
        uint32_t cp;
        i += tui_utf8_decode(q + i, n - i, &cp);
        if (vp_is_space(cp)) {
            pending = m > 0;
            continue;
        }
        if (cp < 0x20)
            continue;
        if (pending)
            v[m++] = ' ';
        pending = 0;
        v[m++] = fold(cp);
    }
    *out = v;
    return m;
}

static int found_add(tui_found *f, size_t *segcap, size_t *hitcap, const tui_hit *h, const tui_seg *segs)
{
    if (f->nhits == *hitcap) {
        size_t cap = *hitcap ? *hitcap * 2 : 16;
        tui_hit *p = realloc(f->hits, cap * sizeof *p);
        if (!p)
            return -1;
        f->hits = p;
        *hitcap = cap;
    }
    if (f->nsegs + h->n > *segcap) {
        size_t cap = *segcap ? *segcap : 16;
        while (cap < f->nsegs + h->n)
            cap *= 2;
        tui_seg *p = realloc(f->segs, cap * sizeof *p);
        if (!p)
            return -1;
        f->segs = p;
        *segcap = cap;
    }
    memcpy(f->segs + f->nsegs, segs, h->n * sizeof *segs);
    f->hits[f->nhits] = (tui_hit){f->nsegs, h->n};
    f->nsegs += h->n;
    f->nhits++;
    return 0;
}

int tui_search_find(size_t nlines, const char *(*line_at)(void *ctx, size_t i), void *ctx, const char *query,
                    tui_found *out)
{
    corpus c = {NULL, NULL, NULL, NULL, 0, 0};
    uint32_t *q = NULL;
    size_t m, segcap = 0, hitcap = 0;
    int rc = 0;
    memset(out, 0, sizeof *out);
    m = query_cps(query, &q);
    if (m == (size_t)-1)
        return -1;
    if (m == 0) {
        free(q);
        return 0;
    }
    if (corpus_build(&c, nlines, line_at, ctx) != 0)
        rc = -1;
    for (size_t i = 0; rc == 0 && i + m <= c.n;) {
        tui_seg segs[64];
        size_t ns = 0;
        if (c.cp[i] != q[0] || memcmp(c.cp + i, q, m * sizeof *q) != 0) {
            i++;
            continue;
        }
        /* A match spans at most m code points, so at most m segments; one per row is enough in practice. */
        for (size_t j = i; j < i + m; j++) {
            tui_seg *last = ns ? &segs[ns - 1] : NULL;
            if (c.row[j] == SEP_ROW)
                continue;
            if (last && last->row == c.row[j] && c.c0[j] <= last->c1) {
                if (c.c1[j] > last->c1)
                    last->c1 = c.c1[j];
            } else if (ns < sizeof segs / sizeof *segs) {
                segs[ns++] = (tui_seg){c.row[j], c.c0[j], c.c1[j]};
            }
        }
        if (ns > 0 && found_add(out, &segcap, &hitcap, &(tui_hit){0, ns}, segs) != 0)
            rc = -1;
        i += m;
    }
    corpus_free(&c);
    free(q);
    if (rc != 0) {
        tui_found_free(out);
        return -1;
    }
    return 0;
}

void tui_found_free(tui_found *f)
{
    free(f->segs);
    free(f->hits);
    memset(f, 0, sizeof *f);
}

void tui_hit_key(const tui_found *f, size_t i, size_t key[4])
{
    const tui_hit *h = &f->hits[i];
    const tui_seg *a = &f->segs[h->first], *b = &f->segs[h->first + h->n - 1];
    key[0] = a->row, key[1] = a->c0, key[2] = b->row, key[3] = b->c1;
}

long tui_found_by_key(const tui_found *f, const size_t key[4])
{
    for (size_t i = 0; i < f->nhits; i++) {
        size_t k[4];
        tui_hit_key(f, i, k);
        if (memcmp(k, key, sizeof k) == 0)
            return (long)i;
    }
    return -1;
}

long tui_search_pick(const tui_found *f, int mode, long base, size_t anchor_row)
{
    long n = (long)f->nhits;
    if (n == 0)
        return -1;
    if (base >= n)
        base = n - 1;
    switch (mode) {
    case TUI_PICK_QUERY:
        for (long i = 0; i < n; i++)
            if (f->segs[f->hits[i].first].row >= anchor_row)
                return i;
        return 0;
    case TUI_PICK_NEXT:
        return base < 0 ? 0 : (base + 1) % n;
    case TUI_PICK_PREV:
        return base < 0 ? n - 1 : (base - 1 + n) % n;
    default:
        return base < 0 ? 0 : base;
    }
}

size_t tui_search_reveal(const tui_scroll *s, const tui_found *f, size_t i)
{
    const tui_hit *h = &f->hits[i];
    size_t first = f->segs[h->first].row, last = f->segs[h->first + h->n - 1].row, third;
    if (s->height == 0 || (first >= s->top && last <= s->top + s->height - 1))
        return s->top;
    third = s->height / 3;
    return first > third ? first - third : 0;
}

size_t tui_found_row(const tui_found *f, long selected, size_t row, tui_span *out, size_t cap)
{
    size_t lo = 0, hi = f->nhits, n = 0;
    while (lo < hi) { /* the first hit that ends on or after row */
        size_t mid = lo + (hi - lo) / 2;
        const tui_hit *h = &f->hits[mid];
        if (f->segs[h->first + h->n - 1].row < row)
            lo = mid + 1;
        else
            hi = mid;
    }
    for (size_t i = lo; i < f->nhits && f->segs[f->hits[i].first].row <= row; i++) {
        const tui_hit *h = &f->hits[i];
        for (size_t j = 0; j < h->n; j++) {
            const tui_seg *s = &f->segs[h->first + j];
            if (s->row == row && s->c1 > s->c0 && n < cap)
                out[n++] = (tui_span){s->c0, s->c1, (long)i == selected};
        }
    }
    return n;
}

char *tui_line_style(const char *line, size_t c0, size_t c1, const char *open, const char *close)
{
    sbuf b = {NULL, 0, 0, 0};
    size_t n = strlen(line), i = 0, col = 0;
    int on = 0;
    while (i < n) {
        if (line[i] == 0x1b) {
            size_t e = esc_len(line + i, n - i);
            if (on) {
                sb_str(&b, close);
                on = 0;
            }
            sb_add(&b, line + i, e);
            i += e;
            continue;
        }
        int w;
        size_t used = char_at(line + i, n - i, &w);
        int in = col >= c0 && col < c1;
        if (w > 0) {
            if (in && !on) {
                sb_str(&b, open);
                on = 1;
            } else if (!in && on) {
                sb_str(&b, close);
                on = 0;
            }
        }
        sb_add(&b, line + i, used);
        col += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    if (on)
        sb_str(&b, close);
    return sb_done(&b);
}

char *tui_line_splice(const char *line, size_t col, size_t width, const char *text)
{
    sbuf b = {NULL, 0, 0, 0};
    size_t n = strlen(line), i = 0, lc = 0, end = col + width;
    while (i < n) { /* before: whole characters that end by col */
        int w;
        size_t used;
        if (line[i] == 0x1b) {
            size_t e = esc_len(line + i, n - i);
            sb_add(&b, line + i, e);
            i += e;
            continue;
        }
        used = char_at(line + i, n - i, &w);
        if (lc + (size_t)(w > 0 ? w : 0) > col)
            break;
        sb_add(&b, line + i, used);
        lc += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    for (size_t k = lc; k < col; k++)
        sb_add(&b, " ", 1);
    sb_str(&b, RESET);
    sb_str(&b, text);
    sb_str(&b, RESET);
    while (i < n) { /* the replaced columns: dropped, their escapes kept */
        int w;
        size_t used;
        if (line[i] == 0x1b) {
            size_t e = esc_len(line + i, n - i);
            sb_add(&b, line + i, e);
            i += e;
            continue;
        }
        used = char_at(line + i, n - i, &w);
        if (lc >= end)
            break;
        lc += (size_t)(w > 0 ? w : 0);
        i += used;
    }
    for (size_t k = end; k < lc; k++) /* a wide character cut by the right edge */
        sb_add(&b, " ", 1);
    sb_add(&b, line + i, n - i);
    return sb_done(&b);
}

#define DIM_ON "\x1b[2m"
#define DIM_OFF "\x1b[22m"

static void rule(sbuf *b, size_t n)
{
    for (size_t i = 0; i < n; i++)
        sb_str(b, "\xe2\x94\x80");
}

int tui_search_box(const char *query, long idx, size_t count, const char *prev_key, const char *next_key, size_t width,
                   tui_lines *out)
{
    static const char placeholder[] = "Find in transcript";
    sbuf top = {NULL, 0, 0, 0}, mid = {NULL, 0, 0, 0}, bot = {NULL, 0, 0, 0};
    char result[48], prev[64], next[64];
    size_t inner, rw = 0, vr, in_w, avail, ctl, room, left, right, pw, nw, sw;
    const char *sep = " \xc2\xb7 ";
    int buttons, rc;
    if (width <= 1) {
        rc = tui_lines_add(out, "\xe2\x94\x8c", 3) | tui_lines_add(out, "\xe2\x94\x82", 3) | tui_lines_add(out, "\xe2\x94\x94", 3);
        return rc ? -1 : 0;
    }
    inner = width - 2;
    if (!*query)
        result[0] = '\0';
    else if (count == 0)
        (void)snprintf(result, sizeof result, "No matches");
    else
        (void)snprintf(result, sizeof result, "%ld/%zu", idx + 1, count);
    vr = tui_fit(result, strlen(result), inner > 3 ? inner - 3 : 0);
    if (vr > 0)
        rw = tui_width(result, vr) + 2;
    in_w = inner > rw ? inner - rw : 0;

    sb_str(&top, "\xe2\x94\x8c");
    rule(&top, inner);
    sb_str(&top, "\xe2\x94\x90");

    sb_str(&mid, "\xe2\x94\x82");
    if (in_w > 0) {
        sb_str(&mid, " ");
        avail = in_w - 1;
        if (avail > 0 && !*query) {
            size_t fit = tui_fit(placeholder, sizeof placeholder - 1, avail), used = 0, first;
            uint32_t cp;
            first = tui_utf8_decode(placeholder, fit, &cp);
            sb_str(&mid, "\x1b[7m" "\x1b[2m");
            sb_add(&mid, placeholder, first);
            sb_str(&mid, DIM_OFF "\x1b[27m");
            sb_str(&mid, DIM_ON);
            sb_add(&mid, placeholder + first, fit - first);
            sb_str(&mid, DIM_OFF);
            used = tui_width(placeholder, fit);
            for (; used < avail; used++)
                sb_add(&mid, " ", 1);
        } else if (avail > 0) {
            size_t total = tui_width(query, strlen(query)), start = 0, shown;
            char *vis;
            if (total >= avail)
                start = total - (avail - 1);
            vis = tui_line_plain(query, start, total);
            if (!vis) {
                free(top.buf);
                free(mid.buf);
                return -1;
            }
            sb_str(&mid, vis);
            shown = tui_width(vis, strlen(vis)) + 1;
            free(vis);
            sb_str(&mid, "\x1b[7m \x1b[27m");
            for (; shown < avail; shown++)
                sb_add(&mid, " ", 1);
        }
    }
    if (vr > 0) {
        sb_str(&mid, DIM_ON " ");
        sb_add(&mid, result, vr);
        sb_str(&mid, " " DIM_OFF);
    }
    sb_str(&mid, "\xe2\x94\x82");

    (void)snprintf(prev, sizeof prev, "\xe2\x86\x91 %s", prev_key);
    (void)snprintf(next, sizeof next, "\xe2\x86\x93 %s", next_key);
    room = inner > 3 ? inner - 3 : 0;
    pw = tui_width(prev, strlen(prev)), nw = tui_width(next, strlen(next)), sw = tui_width(sep, strlen(sep));
    ctl = pw + sw + nw;
    if (ctl > room) {
        (void)snprintf(prev, sizeof prev, "\xe2\x86\x91");
        (void)snprintf(next, sizeof next, "\xe2\x86\x93");
        sep = " ";
        ctl = 1 + 1 + 1;
    }
    buttons = ctl <= room;
    right = buttons && inner > ctl + 2 ? 1 : 0;
    left = inner > (buttons ? ctl + 2 : 0) + right ? inner - (buttons ? ctl + 2 : 0) - right : 0;
    sb_str(&bot, "\xe2\x94\x94");
    rule(&bot, left);
    if (buttons) {
        sb_str(&bot, " ");
        sb_str(&bot, prev);
        sb_str(&bot, sep);
        sb_str(&bot, next);
        sb_str(&bot, " ");
    }
    rule(&bot, right);
    sb_str(&bot, "\xe2\x94\x98");
    if (top.oom || mid.oom || bot.oom) {
        free(top.buf);
        free(mid.buf);
        free(bot.buf);
        return -1;
    }
    rc = tui_lines_add(out, top.buf, top.n) | tui_lines_add(out, mid.buf, mid.n) | tui_lines_add(out, bot.buf, bot.n);
    free(top.buf);
    free(mid.buf);
    free(bot.buf);
    return rc ? -1 : 0;
}