Skip to content
pi-c Documentation
Login

Documentation

/* The model picker's lines; see modelpanel.h. */
#include "tui/modelpanel.h"

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

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

#define MP_RESET "\x1b[0m"
#define MP_BOLD "\x1b[1m"
#define MP_ARROW "\xe2\x86\x92"
#define MP_TICK "\xe2\x9c\x93"
#define MP_DOT " \xc2\xb7 "
#define MP_ELLIPSIS "\xe2\x80\xa6"
#define MP_TITLE "Select a model"
/* the box and the dock have the list from their third line: the top border (or title) and the filter */
#define MP_LIST_LINE 2
/* the widest a status or a key cell gets before the id is cut */
#define MP_STATUS_MAX 24
#define MP_KEY_MAX 16
/* what Enter does, wrapped to this many lines under the selected model's own */
#define MP_ENTER_LINES 2

/* ---- a line being built ---------------------------------------------------------- */

typedef struct {
    char b[2048];
    size_t n;
} mp_buf;

static void mb_add(mp_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 mb_str(mp_buf *b, const char *s) { mb_add(b, s, strlen(s)); }

static void mb_spaces(mp_buf *b, size_t n) {
    while (n-- > 0) {
        mb_add(b, " ", 1);
    }
}

static size_t mp_width(const char *s) { return s ? tui_width(s, strlen(s)) : 0; }

/* S in STYLE, cut to COLS with "…" and padded to PAD columns (0: not padded). */
static void mb_cell(mp_buf *b, const char *style, const char *s, size_t cols, size_t pad) {
    size_t len = strlen(s), full = tui_width(s, len), w;
    mb_str(b, style);
    if (full <= cols) {
        mb_add(b, s, len);
        w = full;
    } else if (cols == 0) {
        w = 0;
    } else {
        size_t take = tui_fit(s, len, cols - 1);
        mb_add(b, s, take);
        mb_str(b, MP_ELLIPSIS);
        w = tui_width(s, take) + 1;
    }
    if (*style) {
        mb_str(b, MP_RESET);
    }
    mb_spaces(b, pad > w ? pad - w : 0);
}

static int mb_line(tui_lines *out, const char *style, const char *text, size_t cols) {
    mp_buf b = {{0}, 0};
    mb_cell(&b, style, text, cols, 0);
    return tui_lines_add(out, b.b, b.n);
}

/* ---- the list's lines ------------------------------------------------------------------ */

enum { MP_HEAD, MP_ROW, MP_MORE };

typedef struct {
    int kind;
    size_t at; /* the index into order (a heading: of its first row) */
} mp_item;

static int mp_action(const tui_mrow *r) { return r->model[0] == '\x01'; }

/* The provider of row R, as LEN bytes of *P; an action's heading is its own. */
static void mp_provider(const tui_mrow *r, const char **p, size_t *len) {
    const char *slash = strchr(r->model, '/');
    if (mp_action(r)) {
        *p = "Endpoints";
        *len = strlen(*p);
        return;
    }
    *p = r->model;
    *len = slash ? (size_t)(slash - r->model) : 0;
}

static int mp_same_provider(const tui_mrow *a, const tui_mrow *b) {
    const char *pa, *pb;
    size_t la, lb;
    mp_provider(a, &pa, &la);
    mp_provider(b, &pb, &lb);
    return la == lb && memcmp(pa, pb, la) == 0;
}

/* The list's items into OUT (room for 2 * n + 1): how many. */
static size_t mp_items(const tui_mlist *m, mp_item *out) {
    size_t k = 0;
    for (size_t i = 0; i < m->n; i++) {
        if (m->grouped && (i == 0 || !mp_same_provider(&m->rows[m->order[i]], &m->rows[m->order[i - 1]]))) {
            out[k++] = (mp_item){MP_HEAD, i};
        }
        out[k++] = (mp_item){MP_ROW, i};
    }
    if (m->n && m->more && *m->more) {
        out[k++] = (mp_item){MP_MORE, 0};
    }
    return k;
}

size_t tui_mpanel_list_len(const tui_mlist *m) {
    mp_item *it = calloc(2 * m->n + 2, sizeof *it);
    size_t n = it ? mp_items(m, it) : 0;
    free(it);
    return n;
}

/* The id shown: without its provider under a heading. */
static const char *mp_id(const tui_mlist *m, const tui_mrow *r) {
    const char *slash = strchr(r->model, '/');
    return m->grouped && slash ? slash + 1 : r->model;
}

/* The name shown: none when it only repeats the id. */
static const char *mp_name(const tui_mlist *m, const tui_mrow *r) {
    const char *slash = strchr(r->model, '/'), *id = slash ? slash + 1 : r->model;
    if (!r->name || !*r->name || strcmp(r->name, id) == 0 || strcmp(r->name, mp_id(m, r)) == 0) {
        return "";
    }
    return r->name;
}

/* Column widths for the rows shown, fitted into COLS after the two marks. */
typedef struct {
    size_t id, name, price, status, key;
} mp_cols;

static size_t mp_total(const mp_cols *c) {
    return 4 + c->id + (c->name ? 2 + c->name : 0) + (c->price ? 2 + c->price : 0) + (c->status ? 2 + c->status : 0) +
           (c->key ? 2 + c->key : 0);
}

static size_t mp_shrink(size_t *w, size_t floor, size_t excess) {
    size_t cut = *w > floor ? *w - floor : 0;
    cut = cut < excess ? cut : excess;
    *w -= cut;
    return excess - cut;
}

static mp_cols mp_columns(const tui_mlist *m, size_t cols) {
    mp_cols c = {0, 0, 0, 0, 0};
    size_t total, excess;
    int keys = 0;
    for (size_t i = 0; i < m->n; i++) {
        const tui_mrow *r = &m->rows[m->order[i]];
        size_t w;
        if (mp_action(r)) {
            continue;
        }
        keys |= r->key != NULL;
        if ((w = mp_width(mp_id(m, r))) > c.id) {
            c.id = w;
        }
        if ((w = mp_width(mp_name(m, r))) > c.name) {
            c.name = w;
        }
        if ((w = mp_width(r->price)) > c.price) {
            c.price = w;
        }
        if ((w = mp_width(r->status)) > c.status) {
            c.status = w;
        }
        if ((w = mp_width(r->key)) > c.key) {
            c.key = w;
        }
    }
    c.status = c.status > MP_STATUS_MAX ? MP_STATUS_MAX : c.status;
    c.key = keys ? (c.key < 3 ? 3 : c.key > MP_KEY_MAX ? MP_KEY_MAX : c.key) : 0;
    total = mp_total(&c);
    if (total <= cols) {
        return c;
    }
    /* too wide: the name narrows, then goes; the key goes; the price goes; the status narrows; the id
     * narrows; the status goes; the id takes what is left (the description has each of them whole) */
    excess = mp_shrink(&c.name, 12, total - cols);
    if (excess && c.name) {
        excess = excess > c.name + 2 ? excess - c.name - 2 : 0;
        c.name = 0;
    }
    if (excess && c.key) {
        excess = excess > c.key + 2 ? excess - c.key - 2 : 0;
        c.key = 0;
    }
    if (excess && c.price) {
        excess = excess > c.price + 2 ? excess - c.price - 2 : 0;
        c.price = 0;
    }
    excess = mp_shrink(&c.status, 10, excess);
    excess = mp_shrink(&c.id, 16, excess);
    if (excess && c.status) {
        c.status = 0;
    }
    if (mp_total(&c) > cols) {
        c.id = cols > 4 ? cols - 4 : 0;
        c.name = c.price = c.status = c.key = 0;
    }
    return c;
}

static int mp_row_line(tui_lines *out, const tui_mlist *m, const tui_mrow *r, const mp_cols *c, int sel, size_t cols) {
    mp_buf b = {{0}, 0};
    const char *accent = tui_fg(TUI_T_ACCENT), *muted = sel ? "" : tui_fg(TUI_T_MUTED);
    if (sel) {
        mb_str(&b, accent);
    }
    mb_str(&b, sel ? MP_ARROW " " : "  ");
    if (mp_action(r)) {
        mb_str(&b, "  ");
        mb_cell(&b, sel ? "" : tui_fg(TUI_T_DIM), r->name ? r->name : "", cols > 4 ? cols - 4 : 0, 0);
        mb_str(&b, MP_RESET);
        return tui_lines_add(out, b.b, b.n);
    }
    if (strcmp(r->model, m->current ? m->current : "") == 0) {
        mb_cell(&b, sel ? "" : accent, MP_TICK, 1, 0);
        if (sel) {
            mb_str(&b, accent);
        }
        mb_str(&b, " ");
    } else {
        mb_str(&b, "  ");
    }
    mb_cell(&b, sel ? "" : r->avail ? "" : tui_fg(TUI_T_DIM), mp_id(m, r), c->id, c->id);
    if (sel) {
        mb_str(&b, accent);
    }
    if (c->name) {
        mb_str(&b, "  ");
        mb_cell(&b, muted, mp_name(m, r), c->name, c->name);
    }
    if (c->price) {
        mb_str(&b, "  ");
        mb_cell(&b, muted, r->price ? r->price : "", c->price, c->price);
    }
    if (c->status) {
        mb_str(&b, "  ");
        mb_cell(&b, sel ? "" : r->warn ? tui_fg(TUI_T_WARNING) : muted, r->status ? r->status : "", c->status, c->status);
    }
    if (c->key) {
        mb_str(&b, "  ");
        mb_cell(&b, muted, r->key ? r->key : "", c->key, c->key);
    }
    mb_str(&b, MP_RESET);
    return tui_lines_add(out, b.b, b.n);
}

/* A heading: the provider in bold, how many of its models are listed muted. */
static int mp_head_line(tui_lines *out, const tui_mlist *m, size_t at, size_t cols) {
    mp_buf b = {{0}, 0};
    const tui_mrow *r = &m->rows[m->order[at]];
    const char *p;
    size_t len, count = 0, w;
    char name[128], more[48];
    mp_provider(r, &p, &len);
    (void)snprintf(name, sizeof name, "%.*s", (int)len, p);
    for (size_t i = at; i < m->n && mp_same_provider(&m->rows[m->order[i]], r); i++) {
        count += !mp_action(&m->rows[m->order[i]]);
    }
    mb_cell(&b, MP_BOLD, name, cols, 0);
    w = mp_width(name);
    if (count > 1 && w + 4 < cols) {
        (void)snprintf(more, sizeof more, "  %zu models", count);
        mb_cell(&b, tui_fg(TUI_T_MUTED), more, cols - w, 0);
    }
    return tui_lines_add(out, b.b, b.n);
}

/* "200k", "1M": a context window, short. */
static void mp_window(long w, char *out, size_t cap) {
    if (w >= 1000000) {
        (void)snprintf(out, cap, "%.3gM", (double)w / 1e6);
    } else {
        (void)snprintf(out, cap, "%ldk", (w + 500) / 1000);
    }
}

/* The description's first line: the selected model's name, context window and price; an action's purpose. */
static void mp_about(const tui_mlist *m, char *out, size_t cap) {
    const tui_mrow *r = m->n ? &m->rows[m->order[m->sel < m->n ? m->sel : 0]] : NULL;
    size_t k;
    if (!r) {
        out[0] = '\0';
        return;
    }
    if (mp_action(r)) {
        (void)snprintf(out, cap, "%s", r->about ? r->about : "");
        return;
    }
    k = (size_t)snprintf(out, cap, "%s", r->name && *r->name ? r->name : r->model);
    if (r->window > 0 && k < cap) {
        char w[32];
        mp_window(r->window, w, sizeof w);
        k += (size_t)snprintf(out + k, cap - k, MP_DOT "%s context", w);
    }
    if (r->price && *r->price && k < cap) {
        k += (size_t)snprintf(out + k, cap - k, MP_DOT "%s", r->price);
    }
    if (r->status && *r->status && k < cap) {
        (void)snprintf(out + k, cap - k, MP_DOT "%s", r->status);
    }
}

/* The keys, wrapped at COLS: never cut. */
static int mp_hints(const tui_mlist *m, size_t cols, tui_lines *out) {
    const char *h = m->hints ? m->hints : "";
    return *h ? tui_wrap(h, strlen(h), cols ? cols : 1, out) : 0;
}

size_t tui_mpanel_chrome(const tui_mlist *m, size_t width) {
    tui_lines h = {NULL, 0, 0};
    size_t n;
    (void)mp_hints(m, width > 4 ? width - 4 : 1, &h);
    n = h.n;
    tui_lines_clear(&h);
    return 5 + MP_ENTER_LINES + n; /* the borders, the filter, the separator, the description, Enter, the keys */
}

/* The position of the selected model among the models (actions aside), and how many there are. */
static void mp_count(const tui_mlist *m, char *out, size_t cap) {
    size_t at = 0, total = 0;
    for (size_t i = 0; i < m->n; i++) {
        if (!mp_action(&m->rows[m->order[i]])) {
            total++;
            at += i <= m->sel;
        }
    }
    (void)snprintf(out, cap, "%zu of %zu", at, total);
}

/* The content lines (no frame): the filter, LIST lines of list, the description, the keys. The filter's
 * cursor column in *fcol. */
static int mp_content(tui_mview *v, const tui_mlist *m, size_t cols, size_t list, tui_lines *out, int *fcol) {
    mp_item *it = calloc(2 * m->n + 2, sizeof *it);
    size_t n, first, k, shown = 0;
    long sel = -1;
    int up, down, rc = 0;
    char line[1200];
    mp_cols c;
    if (!it) {
        return -1;
    }
    n = mp_items(m, it);
    for (size_t i = 0; i < n; i++) {
        if (it[i].kind == MP_ROW && it[i].at == m->sel) {
            sel = (long)i;
        }
    }
    v->page = list;
    /* the filter */
    if (m->filter && *m->filter) {
        (void)snprintf(line, sizeof line, "> %s", m->filter);
        rc |= mb_line(out, "", line, cols);
        *fcol = (int)mp_width(line);
    } else {
        mp_buf b = {{0}, 0};
        mb_str(&b, "> ");
        mb_cell(&b, tui_fg(TUI_T_DIM), "type to filter", cols > 2 ? cols - 2 : 0, 0);
        rc |= tui_lines_add(out, b.b, b.n);
        *fcol = 2;
    }
    if (*fcol >= (int)cols) {
        *fcol = cols ? (int)cols - 1 : 0;
    }
    /* the list */
    if (m->n == 0) {
        if (list > 1) {
            rc |= tui_lines_add(out, "", 0);
            shown++;
        }
        if (m->filter && *m->filter) {
            (void)snprintf(line, sizeof line, "  No model matches \"%s\".", m->filter);
        } else {
            (void)snprintf(line, sizeof line, "  No provider has a key yet: type a name to see its models.");
        }
        rc |= mb_line(out, "", line, cols);
        shown++;
        if (shown < list) {
            rc |= mb_line(out, tui_fg(TUI_T_DIM),
                          m->filter && *m->filter ? "  Backspace widens it; pic models --all lists every model."
                                                  : "  /login adds a key.",
                          cols);
            shown++;
        }
    } else {
        c = mp_columns(m, cols);
        tui_panel_scroll(&v->top, n, sel, list, &first, &k, &up, &down);
        if (up) {
            (void)snprintf(line, sizeof line, "   \xe2\x86\x91 %zu more", first);
            rc |= mb_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].kind == MP_HEAD) {
                rc |= mp_head_line(out, m, it[i].at, cols);
            } else if (it[i].kind == MP_MORE) {
                (void)snprintf(line, sizeof line, "  %s", m->more);
                rc |= mb_line(out, tui_fg(TUI_T_DIM), line, cols);
            } else {
                rc |= mp_row_line(out, m, &m->rows[m->order[it[i].at]], &c, (long)i == sel, cols);
            }
        }
        if (down) {
            (void)snprintf(line, sizeof line, "   \xe2\x86\x93 %zu more", n - first - k);
            rc |= mb_line(out, tui_fg(TUI_T_DIM), line, cols);
            shown++;
        }
    }
    for (; shown < list; shown++) {
        rc |= tui_lines_add(out, "", 0);
    }
    /* the description: the selected row, then what Enter does */
    mp_about(m, line, sizeof line);
    rc |= mb_line(out, "", line, cols);
    {
        tui_lines e = {NULL, 0, 0};
        const char *enter = m->n && m->enter ? m->enter : "";
        rc |= *enter ? tui_wrap(enter, strlen(enter), cols ? cols : 1, &e) : 0;
        for (size_t i = 0; i < MP_ENTER_LINES; i++) {
            if (i + 1 == MP_ENTER_LINES && e.n > MP_ENTER_LINES) {
                char cut[1200];
                (void)snprintf(cut, sizeof cut, "%s %s", e.lines[i], e.lines[i + 1]);
                rc |= mb_line(out, tui_fg(TUI_T_MUTED), cut, cols);
            } else {
                rc |= mb_line(out, tui_fg(TUI_T_MUTED), i < e.n ? e.lines[i] : "", cols);
            }
        }
        tui_lines_clear(&e);
    }
    /* the keys */
    {
        tui_lines h = {NULL, 0, 0};
        rc |= mp_hints(m, cols, &h);
        for (size_t i = 0; i < h.n; i++) {
            rc |= mb_line(out, tui_fg(TUI_T_DIM), h.lines[i], cols);
        }
        tui_lines_clear(&h);
    }
    free(it);
    return rc ? -1 : 0;
}

static int mp_one(const tui_mlist *m, size_t width, tui_lines *out) {
    char head[1200], count[48];
    const tui_mrow *r = m->n ? &m->rows[m->order[m->sel < m->n ? m->sel : 0]] : NULL;
    int rc = 0;
    mp_count(m, count, sizeof count);
    if (!r) {
        (void)snprintf(head, sizeof head, "Model 0/0: no match for \"%s\"", m->filter ? m->filter : "");
        rc |= mb_line(out, "", head, width);
    } else {
        char *of = strstr(count, " of ");
        if (of) {
            memmove(of + 1, of + 4, strlen(of + 4) + 1);
            *of = '/';
        }
        (void)snprintf(head, sizeof head, "Model %s %s%s%s", count, mp_action(r) ? r->name : mp_id(m, r),
                       r->price && *r->price ? " " : "", r->price ? r->price : "");
        rc |= mb_line(out, MP_BOLD, head, width);
    }
    rc |= mb_line(out, tui_fg(TUI_T_DIM), " \xe2\x86\x91\xe2\x86\x93 enter esc \xc2\xb7 widen for more", width);
    return rc;
}

int tui_mpanel_lines(tui_mview *v, const tui_mlist *m, int form, 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, rc;
    char count[48];
    *crow = -1;
    *ccol = 0;
    v->form = form == TUI_PANEL_BOX && width >= 24 ? TUI_PANEL_BOX : form == TUI_PANEL_DOCK && width >= 12 ? TUI_PANEL_DOCK
                                                                                                         : TUI_PANEL_LINE;
    if (v->form == TUI_PANEL_LINE) {
        return mp_one(m, width ? width : 1, out) ? -1 : 0;
    }
    list = list ? list : 1;
    rc = mp_content(v, m, v->form == TUI_PANEL_BOX ? width - 4 : width - 1, list, &c, &fcol);
    mp_count(m, count, sizeof count);
    rc |= tui_panel_frame(v->form, MP_TITLE, count, &c, v->form == TUI_PANEL_BOX ? 1 + list : 0, NULL, width, out);
    *crow = (int)(base + 1);
    *ccol = v->form == TUI_PANEL_BOX ? 2 + fcol : fcol;
    tui_lines_clear(&c);
    return rc ? -1 : 0;
}

long tui_mpanel_click(const tui_mview *v, const tui_mlist *m, size_t line) {
    mp_item *it;
    size_t n, first, k, at, top = v->top;
    long sel = -1, hit = -1;
    int up, down;
    if (v->form == TUI_PANEL_LINE || line < MP_LIST_LINE || line >= MP_LIST_LINE + v->page || !m->n) {
        return -1;
    }
    if (!(it = calloc(2 * m->n + 2, sizeof *it))) {
        return -1;
    }
    n = mp_items(m, it);
    for (size_t i = 0; i < n; i++) {
        if (it[i].kind == MP_ROW && it[i].at == m->sel) {
            sel = (long)i;
        }
    }
    tui_panel_scroll(&top, n, sel, v->page, &first, &k, &up, &down); /* as last drawn */
    at = line - MP_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].kind == MP_ROW) {
            hit = (long)it[i].at;
        }
    }
    free(it);
    return hit;
}