Skip to content
pi-c Artifact [01a172b92d]
Login

Artifact [01a172b92d]

Artifact 01a172b92d174ddf3807240898a974e852e586aaecb30764eebe74f2b364b2f2:


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

#include "view.h"

#define DIM "\x1b[2m"
#define BOLD "\x1b[1m"
#define GREEN "\x1b[32m"
#define RED "\x1b[31m"
#define YELLOW "\x1b[33m"
#define RESET "\x1b[0m"

#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;
} 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, span **out) {
    size_t n = 0, cap = 0;
    span *v = NULL;
    *out = NULL;
    while (*s) {
        size_t k = strcspn(s, "\n");
        if (n == cap) {
            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(span a, span b) { return a.n == b.n && memcmp(a.p, b.p, a.n) == 0; }

static int diff_line(str *out, char mark, span l) {
    return (out->len ? str_add(out, "\n", 1) : 0) || str_add(out, &mark, 1) || str_add(out, l.p, l.n);
}

char *tui_diff_text(const char *old_text, const char *new_text) {
    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]);
    }
    for (size_t i = pre; i < no - suf; i++) {
        (void)diff_line(&out, '-', o[i]);
    }
    for (size_t i = pre; i < nn - suf; i++) {
        (void)diff_line(&out, '+', n[i]);
    }
    for (size_t i = 0; i < suf && i < DIFF_CONTEXT; i++) {
        (void)diff_line(&out, ' ', o[no - suf + i]);
    }
    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};
    if (len == 0) {
        s = "";
    }
    rc |= (size_t)(tui_wrap(s, len, cols > ind + 1 ? cols - ind : 1, &w) != 0);
    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);
    const char *s = is_diff ? t->diff : t->output;
    const char *plain_style = t->state == TUI_TOOL_ERROR ? RED : DIM;
    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] == '-' ? RED : s[0] == '+' ? GREEN : DIM;
            }
            if (add_wrapped(body, style, s, k, cols, "  ") != 0) {
                return -1;
            }
            s += k + (k < len);
            len -= k + (k < len);
        }
    }
    return 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 (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};
        (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)));
        rc |= !styled.buf || tui_wrap(styled.buf, styled.len, cols ? cols : 1, &head) != 0;
        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];
        (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;
}

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

void tui_footer_where(const char *ws, const char *home, const char *branch, const char *name, char *out, size_t cap) {
    size_t hl = home ? strlen(home) : 0;
    int under = hl > 0 && strncmp(ws, home, hl) == 0 && (ws[hl] == '/' || !ws[hl]);
    size_t n = (size_t)snprintf(out, cap, "%s%s", under ? "~" : "", under ? ws + hl : ws);
    if (branch && *branch && n < cap) {
        n += (size_t)snprintf(out + n, cap - n, " (%s)", branch);
    }
    if (name && *name && n < cap) {
        (void)snprintf(out + n, cap - n, " \xe2\x80\xa2 %s", name);
    }
}

void tui_footer_stats(const tui_footer *f, size_t cols, char *out, size_t cap) {
    char left[256], pct[48], tail[256], right[256], num[24];
    size_t n = 0, lw, rw;
    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 (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);
    }
    lw = tui_width(left, strlen(left)) + tui_width(pct, strlen(pct)) + tui_width(tail, strlen(tail));
    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 DIM, strlen(RESET 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));
    }
    (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 (strncmp(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);
    }
}