Skip to content
pi-c Documentation
Login

Documentation

/* The look of tool blocks and the footer; see view.h. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "view.h"
#include "markdown.h"

#include "theme.h"

#define BOLD "\x1b[1m"
#define RESET "\x1b[0m"
/* Pi's theme tokens (theme.h) where the colours used to be hard-coded. */
#define DIM tui_fg(TUI_T_DIM)
#define GREEN tui_fg(TUI_T_SUCCESS)
#define RED tui_fg(TUI_T_ERROR)
#define YELLOW tui_fg(TUI_T_WARNING)

int tui_border_line(const char *status_sgr, const char *status, size_t cols, tui_lines *out) {
    return tui_border_line_in(tui_fg(TUI_T_BORDER), status_sgr, status, cols, out);
}

int tui_border_line_in(const char *color_sgr, const char *status_sgr, const char *status, size_t cols, tui_lines *out) {
    return tui_border_line_titled(color_sgr, status_sgr, status, NULL, cols, out);
}

int tui_border_line_titled(const char *color_sgr, const char *status_sgr, const char *status, const char *title, size_t cols,
                           tui_lines *out) {
    size_t cap = cols * 3 + (status ? strlen(status) : 0) + (title ? strlen(title) : 0) + 128, n = 0, sw = 0, fit = 0;
    size_t left, room, tfit = 0, tw = 0;
    int cut = 0, rc;
    char *b = malloc(cap);
    const char *bc = color_sgr ? color_sgr : tui_fg(TUI_T_BORDER);
    if (!b) {
        return -1;
    }
    if (status && *status && cols >= 6) {
        fit = tui_fit(status, strlen(status), cols - 5);
        sw = tui_width(status, fit);
    }
    left = sw > 0 ? sw + 4 : 0;
    /* the title's room: the row less the status, three "─" after it, and " " TITLE " ──" */
    room = cols > left + 3 + 4 ? cols - left - 3 - 4 : 0;
    if (title && *title && room >= 3) {
        size_t len = strcspn(title, "\n");
        tfit = tui_fit(title, len, room);
        if (tfit < len) { /* cut: the ellipsis takes a column */
            tfit = tui_fit(title, len, room - 1);
            cut = 1;
        }
        tw = tui_width(title, tfit) + (size_t)cut;
    }
    n += (size_t)snprintf(b + n, cap - n, "%s", bc);
    if (sw > 0) {
        n += (size_t)snprintf(b + n, cap - n, "\xe2\x94\x80\xe2\x94\x80 %s%.*s" RESET "%s ", status_sgr ? status_sgr : "", (int)fit, status, bc);
    }
    for (size_t i = left; i + (tw ? tw + 4 : 0) < cols; i++) {
        memcpy(b + n, "\xe2\x94\x80", 3);
        n += 3;
    }
    if (tw) {
        n += (size_t)snprintf(b + n, cap - n, " " RESET "%s%.*s%s" RESET "%s \xe2\x94\x80\xe2\x94\x80", DIM, (int)tfit, title,
                              cut ? "\xe2\x80\xa6" : "", bc);
    }
    n += (size_t)snprintf(b + n, cap - n, RESET);
    rc = tui_lines_add(out, b, n);
    free(b);
    return rc;
}

#define BASH_PREVIEW_LINES 5  /* Pi: BASH_PREVIEW_LINES */
#define OUTPUT_PREVIEW_LINES 10
#define DIFF_PREVIEW_LINES 24
#define HEADER_LINES 4
#define DIFF_CONTEXT 2

void tui_fmt_duration(long ms, char *out, size_t cap) {
    double seconds = (double)(ms < 0 ? 0 : ms) / 1000.0;
    long total, minutes;
    if (seconds < 60) {
        (void)snprintf(out, cap, "%.1fs", seconds);
        return;
    }
    total = (long)seconds;
    minutes = total / 60;
    if (minutes < 60) {
        (void)snprintf(out, cap, "%ldm %lds", minutes, total % 60);
    } else {
        (void)snprintf(out, cap, "%ldh %ldm %lds", minutes / 60, minutes % 60, total % 60);
    }
}

void tui_fmt_tokens(long long n, char *out, size_t cap) {
    if (n < 1000) {
        (void)snprintf(out, cap, "%lld", n);
    } else if (n < 10000) {
        (void)snprintf(out, cap, "%.1fk", (double)n / 1000.0);
    } else if (n < 1000000) {
        (void)snprintf(out, cap, "%lldk", (n + 500) / 1000);
    } else if (n < 10000000) {
        (void)snprintf(out, cap, "%.1fM", (double)n / 1e6);
    } else {
        (void)snprintf(out, cap, "%lldM", (n + 500000) / 1000000);
    }
}

void tui_fmt_size(size_t bytes, char *out, size_t cap) {
    if (bytes < 1024) {
        (void)snprintf(out, cap, "%zuB", bytes);
    } else if (bytes < 1024 * 1024) {
        (void)snprintf(out, cap, "%.1fKB", (double)bytes / 1024.0);
    } else {
        (void)snprintf(out, cap, "%.1fMB", (double)bytes / (1024.0 * 1024.0));
    }
}

/* ---- a growable string ---------------------------------------------------- */

typedef struct {
    char *buf;
    size_t len, cap;
} str;

static int str_add(str *s, const char *p, size_t n) {
    if (s->len + n + 1 > s->cap) {
        size_t cap = s->cap ? s->cap : 256;
        char *grown;
        while (cap < s->len + n + 1) {
            cap *= 2;
        }
        if (!(grown = realloc(s->buf, cap))) {
            return -1;
        }
        s->buf = grown;
        s->cap = cap;
    }
    memcpy(s->buf + s->len, p, n);
    s->len += n;
    s->buf[s->len] = '\0';
    return 0;
}

/* ---- diff ------------------------------------------------------------------ */

typedef struct {
    const char *p;
    size_t n;
} vw_span;

/* The lines of s (a final newline ends the last line instead of starting an
 * empty one). Returns the count; *out is malloc'd. */
static size_t split_lines(const char *s, vw_span **out) {
    size_t n = 0, cap = 0;
    vw_span *v = NULL;
    *out = NULL;
    while (*s) {
        size_t k = strcspn(s, "\n");
        if (n == cap) {
            vw_span *grown = realloc(v, (cap ? cap * 2 : 16) * sizeof *v);
            if (!grown) {
                free(v);
                return (size_t)-1;
            }
            v = grown;
            cap = cap ? cap * 2 : 16;
        }
        v[n].p = s;
        v[n++].n = k;
        s += k + (s[k] == '\n');
    }
    *out = v;
    return n;
}

static int same(vw_span a, vw_span b) { return a.n == b.n && memcmp(a.p, b.p, a.n) == 0; }

/* One diff line: the mark, then (width > 0) Pi's right-aligned line number and a space. */
static int diff_line(str *out, char mark, vw_span l, long num, int width) {
    char pre[40];
    int k = 0;
    if (width > 0) {
        k = snprintf(pre, sizeof pre, "%*ld ", width, num);
    }
    return (out->len ? str_add(out, "\n", 1) : 0) || str_add(out, &mark, 1) || (k > 0 && str_add(out, pre, (size_t)k)) ||
           str_add(out, l.p, l.n);
}

char *tui_diff_text(const char *old_text, const char *new_text) { return tui_diff_numbered(old_text, new_text, 1, 1, 0); }

/* Pi's generateDiffString lines: "-N old", "+N new", " N context" (context numbered
 * by the old file), N right-aligned to width. old_line and new_line are the 1-based
 * lines where the texts start in the old and new file; width 0 leaves numbers off. */
char *tui_diff_numbered(const char *old_text, const char *new_text, long old_line, long new_line, int width) {
    vw_span *o, *n;
    size_t no = split_lines(old_text, &o), nn = split_lines(new_text, &n), pre = 0, suf = 0;
    str out = {NULL, 0, 0};
    if (no == (size_t)-1 || nn == (size_t)-1) {
        free(o);
        free(n);
        return NULL;
    }
    while (pre < no && pre < nn && same(o[pre], n[pre])) {
        pre++;
    }
    while (suf < no - pre && suf < nn - pre && same(o[no - 1 - suf], n[nn - 1 - suf])) {
        suf++;
    }
    if (pre == no && pre == nn) {
        free(o);
        free(n);
        return strdup("");
    }
    for (size_t i = pre > DIFF_CONTEXT ? pre - DIFF_CONTEXT : 0; i < pre; i++) {
        (void)diff_line(&out, ' ', o[i], old_line + (long)i, width);
    }
    for (size_t i = pre; i < no - suf; i++) {
        (void)diff_line(&out, '-', o[i], old_line + (long)i, width);
    }
    for (size_t i = pre; i < nn - suf; i++) {
        (void)diff_line(&out, '+', n[i], new_line + (long)(i), width);
    }
    for (size_t i = 0; i < suf && i < DIFF_CONTEXT; i++) {
        (void)diff_line(&out, ' ', o[no - suf + i], old_line + (long)(no - suf + i), width);
    }
    free(o);
    free(n);
    return out.buf ? out.buf : strdup("");
}

/* ---- tool blocks ------------------------------------------------------------ */

/* Appends s, wrapped to cols and styled with style, each line indented. */
static int add_wrapped(tui_lines *out, const char *style, const char *s, size_t len, size_t cols, const char *indent) {
    tui_lines w = {NULL, 0, 0};
    size_t ind = strlen(indent), rc = 0;
    str t = {NULL, 0, 0};
    char *linked = NULL;
    size_t ln = 0;
    if (len == 0) {
        s = "";
    } else if (tui_links_on() && (linked = tui_linkify(s, len, &ln))) {
        s = linked, len = ln;
    }
    rc |= (size_t)(tui_wrap(s, len, cols > ind + 1 ? cols - ind : 1, &w) != 0);
    free(linked);
    for (size_t i = 0; i < w.n; i++) {
        t.len = 0;
        rc |= (size_t)(str_add(&t, indent, ind) || str_add(&t, style, strlen(style)) ||
                       str_add(&t, w.lines[i], strlen(w.lines[i])) || str_add(&t, RESET, strlen(RESET)) ||
                       tui_lines_add(out, t.buf, t.len));
    }
    tui_lines_clear(&w);
    free(t.buf);
    return rc ? -1 : 0;
}

/* The body lines of a block: the diff coloured by its first column, or the
 * output, wrapped and indented. */
static int body_lines(const tui_tool *t, size_t cols, tui_lines *body) {
    int is_diff = t->diff && *t->diff && !(t->state == TUI_TOOL_ERROR && t->output);
    int is_content = !is_diff && t->content && *t->content && t->state != TUI_TOOL_ERROR;
    const char *s = is_diff ? t->diff : is_content ? t->content : t->output;
    const char *plain_style = t->state == TUI_TOOL_ERROR ? tui_fg(TUI_T_ERROR) : tui_fg(TUI_T_TOOL_OUTPUT);
    if (!s) {
        return 0;
    }
    {
        size_t len = strlen(s);
        while (len > 0 && (s[len - 1] == '\n' || s[len - 1] == '\r')) {
            len--;
        }
        if (len == 0) {
            return 0;
        }
        while (len > 0) {
            size_t k = 0;
            const char *style = plain_style;
            while (k < len && s[k] != '\n') {
                k++;
            }
            if (is_diff) {
                style = s[0] == '-' ? tui_fg(TUI_T_TOOL_DIFF_REMOVED) : s[0] == '+' ? tui_fg(TUI_T_TOOL_DIFF_ADDED) : tui_fg(TUI_T_TOOL_DIFF_CONTEXT);
            }
            if (add_wrapped(body, style, s, k, cols, "  ") != 0) {
                return -1;
            }
            s += k + (k < len);
            len -= k + (k < len);
        }
    }
    return 0;
}

/* The lines of S (its last newline dropped), each wrapped with STYLE: all of them, or the first
 * (KEEP_START) or last N with a hint where the others were. */
static int cm_section(tui_lines *out, const char *style, const char *s, size_t cols, size_t n, int keep_start,
                      const char *noun) {
    size_t len = s ? strlen(s) : 0, count = 0, skip, shown = 0;
    const char *p;
    int rc = 0;
    while (len > 0 && s[len - 1] == '\n') {
        len--;
    }
    if (len == 0) {
        return 0;
    }
    for (size_t i = 0; i < len; i++) {
        count += s[i] == '\n';
    }
    count++;
    skip = n && count > n && !keep_start ? count - n : 0;
    if (skip) {
        char hint[96];
        (void)snprintf(hint, sizeof hint, "... (%zu earlier %s, ctrl+o to expand)", skip, noun);
        rc |= add_wrapped(out, DIM, hint, strlen(hint), cols, "  ");
    }
    p = s;
    for (size_t i = 0; i < count && p < s + len; i++) {
        const char *nl = memchr(p, '\n', (size_t)(s + len - p));
        size_t k = nl ? (size_t)(nl - p) : (size_t)(s + len - p);
        if (i >= skip && (!n || !keep_start || shown < n)) {
            rc |= add_wrapped(out, style, p, k, cols, "  ");
            shown++;
        }
        p += k + 1;
    }
    if (n && keep_start && count > n) {
        char hint[96];
        (void)snprintf(hint, sizeof hint, "... (%zu more %s, ctrl+o to expand)", count - n, noun);
        rc |= add_wrapped(out, DIM, hint, strlen(hint), cols, "  ");
    }
    return rc;
}

int tui_codemode_lines(const tui_tool *t, int expanded, size_t cols, tui_lines *out) {
    static const char *const marks[] = {"\xe2\x97\x8f", "\xe2\x9c\x93", "\xe2\x9c\x97"};
    const char *color = t->state == TUI_TOOL_ERROR ? RED : t->state == TUI_TOOL_OK ? GREEN : YELLOW, *output = t->output;
    char head[160], dur[32];
    int rc;
    (void)snprintf(head, sizeof head, "%s%s%s codemode%s", BOLD, color, marks[t->state], RESET);
    rc = tui_lines_add(out, head, strlen(head));
    rc |= cm_section(out, tui_fg(TUI_T_TOOL_OUTPUT), t->content, cols, expanded ? 0 : 10, 1, "lines");
    if (t->calls && *t->calls) {
        rc |= tui_lines_add(out, "", 0);
        rc |= cm_section(out, DIM, t->calls, cols, expanded ? 0 : 8, 0, "calls");
    }
    /* Pi drops the "Script completed\nWall time N seconds\nOutput:\n" header. */
    if (output && strncmp(output, "Script ", 7) == 0) {
        const char *o = strstr(output, "\nOutput:\n");
        output = o ? o + 9 : output;
    }
    if (t->state != TUI_TOOL_PENDING && output && *output) {
        rc |= tui_lines_add(out, "", 0);
        rc |= cm_section(out, t->state == TUI_TOOL_ERROR ? tui_fg(TUI_T_ERROR) : tui_fg(TUI_T_TOOL_OUTPUT), output, cols,
                         expanded ? 0 : 5, 1, "lines");
    }
    if (t->ms >= 0) {
        char line[64];
        tui_fmt_duration(t->ms, dur, sizeof dur);
        (void)snprintf(line, sizeof line, "%s %s", t->state == TUI_TOOL_PENDING ? "Elapsed" : "Took", dur);
        rc |= add_wrapped(out, DIM, line, strlen(line), cols, "  ");
    }
    return rc ? -1 : 0;
}

int tui_tool_lines(const tui_tool *t, int expanded, size_t cols, tui_lines *out) {
    static const char *const marks[] = {"\xe2\x97\x8f", "\xe2\x9c\x93", "\xe2\x9c\x97"};
    const char *color = t->state == TUI_TOOL_ERROR ? RED : t->state == TUI_TOOL_OK ? GREEN : YELLOW;
    tui_lines head = {NULL, 0, 0}, body = {NULL, 0, 0};
    str h = {NULL, 0, 0};
    size_t limit, shown, hidden = 0, from = 0;
    int bash = strcmp(t->name, "bash") == 0, rc = 0;
    char dur[32];
    if (strcmp(t->name, "codemode") == 0) {
        return tui_codemode_lines(t, expanded, cols, out);
    }
    if (str_add(&h, marks[t->state], strlen(marks[t->state])) || str_add(&h, " ", 1)) {
        return -1;
    }
    /* bash's title already says what it is ("$ cmd"); other tools lead with their name */
    if (!bash && (str_add(&h, t->name, strlen(t->name)) || str_add(&h, " ", 1))) {
        free(h.buf);
        return -1;
    }
    if (str_add(&h, t->title, strlen(t->title))) {
        free(h.buf);
        return -1;
    }
    {
        str styled = {NULL, 0, 0};
        size_t ln = 0;
        char *linked = NULL;
        (void)(str_add(&styled, BOLD, strlen(BOLD)) || str_add(&styled, color, strlen(color)) ||
               str_add(&styled, h.buf, h.len) || str_add(&styled, RESET, strlen(RESET)));
        if (styled.buf && tui_links_on()) {
            linked = tui_linkify(styled.buf, styled.len, &ln);
        }
        rc |= !styled.buf || tui_wrap(linked ? linked : styled.buf, linked ? ln : styled.len, cols ? cols : 1, &head) != 0;
        free(linked);
        free(styled.buf);
    }
    free(h.buf);
    shown = head.n > HEADER_LINES && !expanded ? HEADER_LINES : head.n;
    for (size_t i = 0; i < shown; i++) {
        rc |= tui_lines_add(out, head.lines[i], strlen(head.lines[i]));
    }
    tui_lines_clear(&head);
    rc |= body_lines(t, cols, &body) != 0;
    limit = t->diff && *t->diff ? DIFF_PREVIEW_LINES : bash ? BASH_PREVIEW_LINES : OUTPUT_PREVIEW_LINES;
    if (!expanded && body.n > limit) {
        hidden = body.n - limit;
        if (bash) {
            from = hidden;
        }
    }
    {
        char hint[96];
        if (t->content && *t->content && t->state != TUI_TOOL_ERROR && !(t->diff && *t->diff)) {
            (void)snprintf(hint, sizeof hint, "... (%zu more lines, %zu total, ctrl+o to expand)", hidden, body.n);
        } else {
            (void)snprintf(hint, sizeof hint, "... (%zu %s lines, ctrl+o to expand)", hidden, bash ? "earlier" : "more");
        }
        if (hidden && bash) {
            rc |= add_wrapped(out, DIM, hint, strlen(hint), cols, "  ") != 0;
        }
        for (size_t i = from; i < (hidden && !bash ? limit : body.n); i++) {
            rc |= tui_lines_add(out, body.lines[i], strlen(body.lines[i]));
        }
        if (hidden && !bash) {
            rc |= add_wrapped(out, DIM, hint, strlen(hint), cols, "  ") != 0;
        }
    }
    tui_lines_clear(&body);
    if (t->ms >= 0) {
        char line[64];
        tui_fmt_duration(t->ms, dur, sizeof dur);
        (void)snprintf(line, sizeof line, "%s %s", t->state == TUI_TOOL_PENDING ? "Elapsed" : "Took", dur);
        rc |= add_wrapped(out, DIM, line, strlen(line), cols, "  ") != 0;
    }
    return rc ? -1 : 0;
}

/* ---- user bash blocks --------------------------------------------------------- */

#define BASH_USER_PREVIEW 20
#define BASH_USER_MAX_LINES 2000

/* The output without escape sequences, CRLF and CR as LF. */
static char *clean_output(const char *s) {
    size_t n = strlen(s), o = 0;
    char *out = malloc(n + 1);
    if (!out) {
        return NULL;
    }
    for (size_t i = 0; i < n; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c == 0x1b) {
            if (i + 1 < n && s[i + 1] == '[') {
                i += 2;
                while (i < n && !((unsigned char)s[i] >= 0x40 && (unsigned char)s[i] <= 0x7e)) {
                    i++;
                }
            } else if (i + 1 < n && s[i + 1] == ']') {
                i += 2;
                while (i < n && s[i] != '\a' && !(s[i] == 0x1b && i + 1 < n && s[i + 1] == '\\')) {
                    i++;
                }
                i += i < n && s[i] == 0x1b;
            } else {
                i++;
            }
        } else if (c == '\r') {
            out[o++] = '\n';
            if (i + 1 < n && s[i + 1] == '\n') {
                i++;
            }
        } else if (c >= 0x20 || c == '\n' || c == '\t') {
            out[o++] = (char)c;
        }
    }
    out[o] = '\0';
    return out;
}

int tui_bash_lines(const tui_bash *b, int expanded, size_t cols, tui_lines *out) {
    const char *color = b->no_context ? DIM : tui_fg(TUI_T_BASH_MODE);
    char *text = clean_output(b->output ? b->output : ""), *first;
    size_t len, nl = 0, avail, shown, hidden, rows_from = 0;
    str rule = {NULL, 0, 0}, head = {NULL, 0, 0}, status = {NULL, 0, 0};
    tui_lines body = {NULL, 0, 0};
    int rc = 0;
    if (!text) {
        return -1;
    }
    len = strlen(text);
    while (len > 0 && text[len - 1] == '\n') {
        text[--len] = '\0';
    }
    first = text;
    if (len > 0) { /* the last 2000 lines at most */
        for (size_t i = 0; i < len; i++) {
            nl += text[i] == '\n';
        }
        avail = nl + 1;
        while (avail > BASH_USER_MAX_LINES) {
            first = strchr(first, '\n') + 1;
            avail--;
        }
    } else {
        avail = 0;
    }
    hidden = !expanded && avail > BASH_USER_PREVIEW ? avail - BASH_USER_PREVIEW : 0;
    for (size_t i = 0; i < hidden; i++) {
        first = strchr(first, '\n') + 1;
    }
    shown = avail - hidden;
    for (size_t i = 0; i < cols; i++) {
        rc |= str_add(&rule, "\xe2\x94\x80", 3);
    }
    rc |= str_add(&head, BOLD, strlen(BOLD)) || str_add(&head, color, strlen(color)) || str_add(&head, "$ ", 2) ||
          str_add(&head, b->command, strlen(b->command)) || str_add(&head, RESET, strlen(RESET));
    rc |= tui_lines_add(out, "", 0);
    if (rule.buf) {
        str colored = {NULL, 0, 0};
        rc |= str_add(&colored, color, strlen(color)) || str_add(&colored, rule.buf, rule.len) ||
              str_add(&colored, RESET, strlen(RESET)) || tui_lines_add(out, colored.buf, colored.len);
        free(colored.buf);
    }
    {
        tui_lines h = {NULL, 0, 0};
        rc |= tui_wrap(head.buf, head.len, cols ? cols : 1, &h);
        for (size_t i = 0; i < h.n; i++) {
            rc |= tui_lines_add(out, h.lines[i], strlen(h.lines[i]));
        }
        tui_lines_clear(&h);
    }
    if (shown > 0) {
        const char *p = first;
        for (size_t i = 0; i < shown; i++) {
            size_t k = strcspn(p, "\n");
            rc |= add_wrapped(&body, DIM, p, k, cols, "") != 0;
            p += k + (p[k] == '\n');
        }
        if (!expanded && body.n > BASH_USER_PREVIEW) {
            rows_from = body.n - BASH_USER_PREVIEW;
        }
        for (size_t i = rows_from; i < body.n; i++) {
            rc |= tui_lines_add(out, body.lines[i], strlen(body.lines[i]));
        }
    }
    if (b->state == TUI_BASH_RUNNING) {
        char line[96];
        (void)snprintf(line, sizeof line, "%sRunning... (esc to cancel)" RESET, DIM);
        rc |= tui_lines_add(out, line, strlen(line));
    } else {
        char line[96];
        if (hidden) {
            (void)snprintf(line, sizeof line, "%s... %zu more lines (ctrl+o to expand)" RESET, DIM, hidden);
            rc |= tui_lines_add(out, line, strlen(line));
        } else if (expanded && avail > BASH_USER_PREVIEW) {
            (void)snprintf(line, sizeof line, "%s(ctrl+o to collapse)" RESET, DIM);
            rc |= tui_lines_add(out, line, strlen(line));
        }
        if (b->state == TUI_BASH_CANCELLED) {
            (void)snprintf(line, sizeof line, "%s(cancelled)" RESET, YELLOW);
            rc |= tui_lines_add(out, line, strlen(line));
        } else if (b->exit_code != 0) {
            (void)snprintf(line, sizeof line, "%s(exit %d)" RESET, RED, b->exit_code);
            rc |= tui_lines_add(out, line, strlen(line));
        }
    }
    if (rule.buf) {
        str colored = {NULL, 0, 0};
        rc |= str_add(&colored, color, strlen(color)) || str_add(&colored, rule.buf, rule.len) ||
              str_add(&colored, RESET, strlen(RESET)) || tui_lines_add(out, colored.buf, colored.len);
        free(colored.buf);
    }
    tui_lines_clear(&body);
    free(rule.buf);
    free(head.buf);
    free(status.buf);
    free(text);
    return rc ? -1 : 0;
}

char *tui_bash_context(const char *command, const char *output, int cancelled, int exit_code) {
    char *text = clean_output(output ? output : ""), *first, *out;
    size_t len, lines = 1, cut = 0;
    str t = {NULL, 0, 0};
    int rc = 0;
    if (!text) {
        return NULL;
    }
    len = strlen(text);
    while (len > 0 && text[len - 1] == '\n') {
        text[--len] = '\0';
    }
    first = text;
    for (size_t i = 0; i < len; i++) {
        lines += text[i] == '\n';
    }
    while (len > 0 && lines > BASH_USER_MAX_LINES) {
        first = strchr(first, '\n') + 1;
        lines--;
        cut = 1;
    }
    if (strlen(first) > 50u * 1024u) { /* by bytes: from the start of a line when there is one */
        char *p = first + strlen(first) - 50u * 1024u, *nl = strchr(p, '\n');
        first = nl ? nl + 1 : p;
        cut = 1;
    }
    rc |= str_add(&t, "Ran `", 5) || str_add(&t, command, strlen(command)) || str_add(&t, "`\n", 2);
    if (*first) {
        rc |= str_add(&t, "```\n", 4) || str_add(&t, first, strlen(first)) || str_add(&t, "\n```", 4);
    } else {
        rc |= str_add(&t, "(no output)", 11);
    }
    if (cancelled) {
        rc |= str_add(&t, "\n\n(command cancelled)", 22);
    } else if (exit_code != 0) {
        char line[64];
        (void)snprintf(line, sizeof line, "\n\nCommand exited with code %d", exit_code);
        rc |= str_add(&t, line, strlen(line));
    }
    if (cut) {
        rc |= str_add(&t, "\n\n[Output truncated]", 20);
    }
    free(text);
    out = rc ? NULL : t.buf;
    if (rc) {
        free(t.buf);
    }
    return out;
}

/* ---- startup ------------------------------------------------------------------- */

void tui_startup_hints(char *out, size_t cap) {
    static const char *const hints[][2] = {{"esc", "interrupt"}, {"ctrl+c/ctrl+d", "clear/exit"}, {"/", "commands"},
                                           {"!", "bash"},       {"ctrl+o", "more"}};
    size_t n = 0;
    out[0] = '\0';
    for (size_t i = 0; i < sizeof hints / sizeof hints[0] && n < cap; i++) {
        if (i) {
            n += (size_t)snprintf(out + n, cap - n, "%s \xc2\xb7 " RESET, DIM);
        }
        n += (size_t)snprintf(out + n, cap - n, "%s%s" RESET " %s", DIM, hints[i][0], hints[i][1]);
    }
}

static int cmp_name(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }

int tui_loaded_section(const char *name, const char *const *items, size_t n, int sort, size_t cols, tui_lines *out) {
    const char **v;
    str line = {NULL, 0, 0};
    tui_lines w = {NULL, 0, 0};
    int rc = 0;
    if (n == 0) {
        return 0;
    }
    v = malloc(n * sizeof *v);
    if (!v) {
        return -1;
    }
    memcpy((void *)v, items, n * sizeof *v);
    if (sort) {
        qsort((void *)v, n, sizeof *v, cmp_name);
    }
    rc |= str_add(&line, "  ", 2);
    for (size_t i = 0; i < n; i++) {
        rc |= (i ? str_add(&line, ", ", 2) : 0) || str_add(&line, v[i], strlen(v[i]));
    }
    {
        char head[160];
        (void)snprintf(head, sizeof head, BOLD "%s[%s]" RESET, tui_fg(TUI_T_MD_HEADING), name);
        rc |= tui_lines_add(out, head, strlen(head));
    }
    rc |= add_wrapped(&w, DIM, line.buf, line.len, cols, "") != 0;
    for (size_t i = 0; i < w.n; i++) {
        rc |= tui_lines_add(out, w.lines[i], strlen(w.lines[i]));
    }
    tui_lines_clear(&w);
    free(line.buf);
    free(v);
    return rc ? -1 : 0;
}

void tui_title(const char *workspace, const char *name, char *out, size_t cap) {
    const char *base = workspace;
    char dir[256], nm[256];
    size_t o = 0;
    size_t wl = strlen(workspace);
    while (wl > 1 && workspace[wl - 1] == '/') {
        wl--;
    }
    for (size_t i = 0; i + 1 < wl; i++) { /* after the last slash that is not the whole path */
        if (workspace[i] == '/') {
            base = workspace + i + 1;
        }
    }
    (void)snprintf(dir, sizeof dir, "%.*s", (int)(wl - (size_t)(base - workspace)), base);
    for (size_t i = 0; name && name[i] && o + 1 < sizeof nm; i++) {
        if ((unsigned char)name[i] >= 0x20 && name[i] != 0x7f) {
            nm[o++] = name[i];
        }
    }
    nm[o] = '\0';
    for (size_t i = 0, k = 0; ; i++) { /* the directory too: drop control bytes in place */
        if ((unsigned char)dir[i] >= 0x20 && dir[i] != 0x7f) {
            dir[k++] = dir[i];
        }
        if (!dir[i]) {
            break;
        }
    }
    if (nm[0]) {
        (void)snprintf(out, cap, "\x1b]0;pic - %s - %s\x07", nm, dir);
    } else {
        (void)snprintf(out, cap, "\x1b]0;pic - %s\x07", dir);
    }
}

/* ---- footer ------------------------------------------------------------------ */

void tui_fit_path(const char *path, size_t cols, char *out, size_t cap) {
    size_t len = strlen(path), at = 0;
    if (tui_width(path, len) <= cols || cols < 2) {
        (void)snprintf(out, cap, "%s", path);
        return;
    }
    while (at < len && tui_width(path + at, len - at) > cols - 1) {
        at++;
        while (at < len && ((unsigned char)path[at] & 0xC0) == 0x80) {
            at++; /* a whole character */
        }
    }
    (void)snprintf(out, cap, "\xe2\x80\xa6%s", path + at);
}

void tui_footer_where(const char *ws, const char *home, const char *branch, const char *name, size_t cols, char *out,
                      size_t cap) {
    size_t hl = home ? strlen(home) : 0, n = 0, pw;
    int under = hl > 0 && strncmp(ws, home, hl) == 0 && (ws[hl] == '/' || !ws[hl]);
    char path[1024], rest[512];
    (void)snprintf(path, sizeof path, "%s%s", under ? "~" : "", under ? ws + hl : ws);
    rest[0] = '\0';
    if (branch && *branch) {
        n += (size_t)snprintf(rest + n, sizeof rest - n, " (%s)", branch);
    }
    if (name && *name && n < sizeof rest) {
        (void)snprintf(rest + n, sizeof rest - n, " \xe2\x80\xa2 %s", name);
    }
    pw = tui_width(path, strlen(path));
    if (cols > 0) {
        size_t rw = tui_width(rest, strlen(rest));
        if (pw + rw > cols && rw + 8 <= cols) { /* the path gives way from the left, keeping its end */
            char fit[1024];
            tui_fit_path(path, cols - rw, fit, sizeof fit);
            (void)snprintf(path, sizeof path, "%s", fit);
        }
    }
    (void)snprintf(out, cap, "%s%s", path, rest);
}

void tui_footer_stats(const tui_footer *f, size_t cols, char *out, size_t cap) {
    char left[256], pct[48], tail[256], right[320], num[24];
    size_t n = 0, lw, rw, aw = 0;
    double used = f->window > 0 ? 100.0 * (double)f->context / (double)f->window : 0;
    const char *hot = used > 90 ? RED : used > 70 ? YELLOW : NULL;
    str line = {NULL, 0, 0};
    left[0] = tail[0] = '\0';
    if (f->in) {
        tui_fmt_tokens(f->in, num, sizeof num);
        n += (size_t)snprintf(left + n, sizeof left - n, "%s\xe2\x86\x91%s", n ? " " : "", num);
    }
    if (f->out) {
        tui_fmt_tokens(f->out, num, sizeof num);
        n += (size_t)snprintf(left + n, sizeof left - n, "%s\xe2\x86\x93%s", n ? " " : "", num);
    }
    if (f->cache_read) {
        tui_fmt_tokens(f->cache_read, num, sizeof num);
        n += (size_t)snprintf(left + n, sizeof left - n, "%sR%s", n ? " " : "", num);
    }
    if (f->cache_write) {
        tui_fmt_tokens(f->cache_write, num, sizeof num);
        n += (size_t)snprintf(left + n, sizeof left - n, "%sW%s", n ? " " : "", num);
    }
    if (f->cost > 0) {
        n += (size_t)snprintf(left + n, sizeof left - n, "%s$%.3f", n ? " " : "", f->cost);
    }
    if (n) {
        (void)strncat(left, " ", sizeof left - strlen(left) - 1);
    }
    if (f->window > 0) {
        char w[24];
        tui_fmt_tokens(f->window, w, sizeof w);
        (void)snprintf(pct, sizeof pct, "%.1f%%/%s", used, w);
    } else {
        tui_fmt_tokens(f->context, num, sizeof num);
        (void)snprintf(pct, sizeof pct, "%s", num);
    }
    if (f->expanded) {
        (void)snprintf(tail, sizeof tail, " \xe2\x80\xa2 tools expanded");
    }
    if (f->level && *f->level) {
        (void)snprintf(right, sizeof right, "%s \xe2\x80\xa2 %s%s", f->model, strcmp(f->level, "off") == 0 ? "thinking " : "",
                       f->level);
    } else {
        (void)snprintf(right, sizeof right, "%s", f->model);
    }
    if (f->key && *f->key) {
        size_t rn = strlen(right);
        (void)snprintf(right + rn, sizeof right - rn, " \xc2\xb7 key %s", f->key);
    }
    lw = tui_width(left, strlen(left)) + tui_width(pct, strlen(pct)) + tui_width(tail, strlen(tail));
    if (f->alert && *f->alert) { /* the warning keeps its room while the stats fit */
        aw = 2 + tui_width(f->alert, strlen(f->alert));
        if (lw + aw < cols) {
            cols -= aw;
        } else {
            aw = 0;
        }
    }
    rw = tui_width(right, strlen(right));
    if (lw + 2 + rw > cols && strchr(f->model, '/')) { /* Pi shows the model's id: the provider goes first */
        const char *id = strchr(f->model, '/') + 1;
        if (f->level && *f->level) {
            (void)snprintf(right, sizeof right, "%s \xe2\x80\xa2 %s%s", id, strcmp(f->level, "off") == 0 ? "thinking " : "",
                           f->level);
        } else {
            (void)snprintf(right, sizeof right, "%s", id);
        }
        if (f->key && *f->key) {
            size_t rn = strlen(right);
            (void)snprintf(right + rn, sizeof right - rn, " \xc2\xb7 key %s", f->key);
        }
        rw = tui_width(right, strlen(right));
    }
    (void)str_add(&line, DIM, strlen(DIM));
    if (lw + 2 + rw > cols) { /* the model gives way first, then the stats */
        if (lw + 2 >= cols) {
            right[0] = '\0';
            rw = 0;
        } else {
            right[tui_fit(right, strlen(right), cols - lw - 2)] = '\0';
            rw = tui_width(right, strlen(right));
        }
    }
    {
        size_t room = cols > 0 ? cols : 1, fit;
        fit = tui_fit(left, strlen(left), room);
        (void)str_add(&line, left, fit);
        room -= tui_width(left, fit);
        if (fit == strlen(left)) {
            if (hot) {
                (void)str_add(&line, hot, strlen(hot));
            }
            fit = tui_fit(pct, strlen(pct), room);
            (void)str_add(&line, pct, fit);
            room -= tui_width(pct, fit);
            if (hot) {
                (void)str_add(&line, RESET, strlen(RESET));
                (void)str_add(&line, DIM, strlen(DIM));
            }
            if (fit == strlen(pct)) {
                fit = tui_fit(tail, strlen(tail), room);
                (void)str_add(&line, tail, fit);
            }
        }
    }
    if (rw) {
        for (size_t pad = cols - lw - rw; pad > 0; pad--) {
            (void)str_add(&line, " ", 1);
        }
        (void)str_add(&line, right, strlen(right));
    } else if (aw) {
        for (size_t pad = cols - lw; pad > 0; pad--) {
            (void)str_add(&line, " ", 1);
        }
    }
    if (aw) {
        (void)str_add(&line, "  ", 2);
        (void)str_add(&line, RESET, strlen(RESET));
        (void)str_add(&line, RED, strlen(RED));
        (void)str_add(&line, f->alert, strlen(f->alert));
    }
    (void)str_add(&line, RESET, strlen(RESET));
    (void)snprintf(out, cap, "%s", line.buf ? line.buf : "");
    free(line.buf);
}

/* ---- git branch ---------------------------------------------------------------- */

static int read_small(const char *path, char *buf, size_t cap) {
    FILE *f = fopen(path, "r");
    size_t n;
    if (!f) {
        return -1;
    }
    n = fread(buf, 1, cap - 1, f);
    (void)fclose(f);
    buf[n] = '\0';
    buf[strcspn(buf, "\r\n")] = '\0';
    return 0;
}

int tui_git_branch(const char *dir, char *out, size_t cap) {
    char cur[1024];
    out[0] = '\0';
    (void)snprintf(cur, sizeof cur, "%s", dir);
    for (int depth = 0; depth < 32; depth++) {
        char path[1100], head[512];
        (void)snprintf(path, sizeof path, "%s/.git/HEAD", cur);
        if (read_small(path, head, sizeof head) != 0) {
            /* a worktree or submodule: .git is a file "gitdir: PATH" */
            (void)snprintf(path, sizeof path, "%s/.git", cur);
            if (read_small(path, head, sizeof head) == 0 && strncmp(head, "gitdir: ", 8) == 0) {
                if (head[8] == '/') {
                    (void)snprintf(path, sizeof path, "%s/HEAD", head + 8);
                } else {
                    (void)snprintf(path, sizeof path, "%s/%s/HEAD", cur, head + 8);
                }
                if (read_small(path, head, sizeof head) != 0) {
                    head[0] = '\0';
                }
            } else {
                head[0] = '\0';
            }
        }
        if (strlen(head) > 16 && memcmp(head, "ref: refs/heads/", 16) == 0) {
            (void)snprintf(out, cap, "%s", head + 16);
            return 1;
        }
        if (head[0]) {
            (void)snprintf(out, cap, "detached");
            return 1;
        }
        {
            char *slash = strrchr(cur, '/');
            if (!slash || slash == cur) {
                break;
            }
            *slash = '\0';
        }
    }
    return 0;
}

void tui_retry_status(int attempt, int max_attempts, long delay_ms, long elapsed_ms, char *out, size_t cap) {
    if (delay_ms > 0) {
        long left = delay_ms - elapsed_ms;
        (void)snprintf(out, cap, "Retrying (%d/%d) in %lds\xe2\x80\xa6 (esc to cancel)", attempt, max_attempts,
                       left > 0 ? (left + 999) / 1000 : 0);
    } else {
        (void)snprintf(out, cap, "Retrying (%d/%d)\xe2\x80\xa6 (esc to cancel)", attempt, max_attempts);
    }
}