Skip to content
pi-c Documentation
Login

Documentation

/* Pi's theme model: tokens, theme files, colour conversion; see theme.h. The
 * OKHSL conversion is a port of Pi's (packages/tui/src/oklab.ts), itself
 * Bjorn Ottosson's reference implementation (MIT). */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include "tui/theme.h"

#include <ctype.h>
#include <stdarg.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "tui/mjson.h"

static const char *const token_names[TUI_T_N] = {
#define X(id, name) #name,
    TUI_TOKENS(X)
#undef X
};

/* Pi's token fallbacks: the optional tokens and what they inherit. */
static const struct {
    tui_token token, fallback;
} fallbacks[] = {
    {TUI_T_SCROLLBAR_TRACK, TUI_T_MUTED},
    {TUI_T_SCROLLBAR_THUMB, TUI_T_TEXT},
    {TUI_T_SEARCH_MATCH_BG, TUI_T_SELECTED_BG},
    {TUI_T_SEARCH_MATCH_TEXT, TUI_T_TEXT},
    {TUI_T_THINKING_MAX, TUI_T_THINKING_XHIGH},
};

static int optional_token(int t)
{
    for (size_t i = 0; i < sizeof fallbacks / sizeof fallbacks[0]; i++)
        if ((int)fallbacks[i].token == t)
            return 1;
    return 0;
}

const char *tui_token_name(tui_token t)
{
    return (int)t >= 0 && t < TUI_T_N ? token_names[t] : NULL;
}

int tui_token_index(const char *name)
{
    for (int i = 0; name && i < TUI_T_N; i++)
        if (strcmp(token_names[i], name) == 0)
            return i;
    return -1;
}

/* ---- OKHSL <-> sRGB ------------------------------------------------------- */

typedef double vec[3];

static void mul(const double m[3][3], const double v[3], double out[3])
{
    for (int i = 0; i < 3; i++)
        out[i] = m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2];
}

static const double LAB_TO_LMS[3][3] = {
    {1, 0.3963377773761749, 0.2158037573099136},
    {1, -0.1055613458156586, -0.0638541728258133},
    {1, -0.0894841775298119, -1.2914855480194092},
};
static const double LMS_TO_LINEAR_SRGB[3][3] = {
    {4.0767416360759583, -3.3077115392580629, 0.2309699031821043},
    {-1.2684379732850315, 2.6097573492876882, -0.341319376002657},
    {-0.0041960761386756, -0.7034186179359362, 1.7076146940746117},
};
static const double SAT_FIT_AB[3][2] = {{-1.8817031, -0.80936501}, {1.8144408, -1.19445267}, {0.13110758, 1.81333971}};
static const double SAT_FIT_K[3][5] = {
    {1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245},
    {0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204},
    {1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167},
};
#define K1 0.206
#define K2 0.03
#define K3 ((1 + K1) / (1 + K2))

static double okhsl_to_oklab_l(double x)
{
    return (x * x + K1 * x) / (K3 * (x + K2));
}

static double linear_to_srgb(double v)
{
    return v > 0.0031308 ? 1.055 * pow(v, 1 / 2.4) - 0.055 : 12.92 * v;
}

static void oklab_to_linear_srgb(const double lab[3], double out[3])
{
    double lms[3];
    mul(LAB_TO_LMS, lab, lms);
    for (int i = 0; i < 3; i++)
        lms[i] = pow(lms[i], 3);
    mul(LMS_TO_LINEAR_SRGB, lms, out);
}

/* JS Math.round for the non-negative values here. */
static int js_round(double v)
{
    return (int)floor(v + 0.5);
}

static void linear_to_rgb(const double lin[3], int *r, int *g, int *b)
{
    int *o[3] = {r, g, b};
    for (int i = 0; i < 3; i++) {
        double v = linear_to_srgb(lin[i]);
        v = v < 0 ? 0 : v > 1 ? 1 : v;
        *o[i] = js_round(v * 255);
    }
}

static void lms_slopes(double a, double b, double out[3])
{
    for (int i = 0; i < 3; i++)
        out[i] = LAB_TO_LMS[i][1] * a + LAB_TO_LMS[i][2] * b;
}

static double max_saturation(double a, double b)
{
    int ch = 2;
    for (int i = 0; i < 2; i++)
        if (SAT_FIT_AB[i][0] * a + SAT_FIT_AB[i][1] * b > 1) {
            ch = i;
            break;
        }
    const double *k = SAT_FIT_K[ch], *w = LMS_TO_LINEAR_SRGB[ch];
    double sat = k[0] + k[1] * a + k[2] * b + k[3] * a * a + k[4] * a * b;
    double sl[3], base[3], f = 0, f1 = 0, f2 = 0;
    lms_slopes(a, b, sl);
    for (int i = 0; i < 3; i++) {
        base[i] = 1 + sat * sl[i];
        f += w[i] * pow(base[i], 3);
        f1 += w[i] * (3 * sl[i] * pow(base[i], 2));
        f2 += w[i] * (6 * pow(sl[i], 2) * base[i]);
    }
    return sat - (f * f1) / (f1 * f1 - 0.5 * f * f2);
}

static void cusp(double a, double b, double out[2])
{
    double sat = max_saturation(a, b), lab[3] = {1, sat * a, sat * b}, lin[3], mx;
    oklab_to_linear_srgb(lab, lin);
    mx = fmax(lin[0], fmax(lin[1], lin[2]));
    out[0] = cbrt(1 / mx);
    out[1] = out[0] * sat;
}

static double max_chroma(double a, double b, double l, const double c[2])
{
    if (l <= c[0])
        return (c[1] * l) / c[0];
    double t = (c[1] * (l - 1)) / (c[0] - 1), sl[3], lms[3], cubes[3], first[3], second[3], best = 1.7976931348623157e308;
    lms_slopes(a, b, sl);
    for (int i = 0; i < 3; i++) {
        lms[i] = l + t * sl[i];
        cubes[i] = pow(lms[i], 3);
        first[i] = 3 * sl[i] * pow(lms[i], 2);
        second[i] = 6 * pow(sl[i], 2) * lms[i];
    }
    for (int r = 0; r < 3; r++) {
        const double *row = LMS_TO_LINEAR_SRGB[r];
        double f = row[0] * cubes[0] + row[1] * cubes[1] + row[2] * cubes[2] - 1;
        double f1 = row[0] * first[0] + row[1] * first[1] + row[2] * first[2];
        double f2 = row[0] * second[0] + row[1] * second[1] + row[2] * second[2];
        double u = f1 / (f1 * f1 - 0.5 * f * f2);
        double step = u >= 0 ? -f * u : 1.7976931348623157e308;
        if (step < best)
            best = step;
    }
    return t + best;
}

static void chroma_stops(double l, double a, double b, double out[3])
{
    double pk[2];
    cusp(a, b, pk);
    double cmax = max_chroma(a, b, l, pk);
    double k = cmax / fmin(l * (pk[1] / pk[0]), (1 - l) * (pk[1] / (1 - pk[0])));
    double mid_s = 0.11516993 +
                   1 / (7.4477897 + 4.1590124 * b +
                        a * (-2.19557347 + 1.75198401 * b +
                             a * (-2.13704948 - 10.02301043 * b + a * (-4.24894561 + 5.38770819 * b + 4.69891013 * a))));
    double mid_t = 0.11239642 +
                   1 / (1.6132032 - 0.68124379 * b +
                        a * (0.40370612 + 0.90148123 * b +
                             a * (-0.27087943 + 0.6122399 * b + a * (0.00299215 - 0.45399568 * b - 0.14661872 * a))));
    double cmid = 0.9 * k * sqrt(sqrt(1 / (1 / pow(l * mid_s, 4) + 1 / pow((1 - l) * mid_t, 4))));
    double c0 = sqrt(1 / (1 / pow(l * 0.4, 2) + 1 / pow((1 - l) * 0.8, 2)));
    out[0] = c0;
    out[1] = cmid;
    out[2] = cmax;
}

void tui_okhsl_to_rgb(double h, double s, double l, int *r, int *g, int *b)
{
    double L = okhsl_to_oklab_l(l), lab[3] = {L, 0, 0}, lin[3];
    if (L > 0 && L < 1 && s > 0) {
        double deg = fmod(fmod(h, 360) + 360, 360), angle = (2 * M_PI * deg) / 360, a = cos(angle), bb = sin(angle), st[3], chroma;
        chroma_stops(L, a, bb, st);
        if (s < 0.8) {
            double t = 1.25 * s, k1 = 0.8 * st[0];
            chroma = (t * k1) / (1 - (1 - k1 / st[1]) * t);
        } else {
            double t = 5 * (s - 0.8), k1 = (0.2 * pow(st[1], 2) * pow(1.25, 2)) / st[0];
            chroma = st[1] + (t * k1) / (1 - (1 - k1 / (st[2] - st[1])) * t);
        }
        lab[1] = chroma * a;
        lab[2] = chroma * bb;
    }
    oklab_to_linear_srgb(lab, lin);
    linear_to_rgb(lin, r, g, b);
}

/* oklch -> sRGB, gamut-mapped by reducing chroma as Pi's oklchToRgb does. */
static int in_gamut(const double lin[3])
{
    for (int i = 0; i < 3; i++)
        if (lin[i] < -1e-7 || lin[i] > 1 + 1e-7)
            return 0;
    return 1;
}

static void oklch_to_rgb(double l, double c, double h, int *r, int *g, int *b)
{
    double rad = (h * M_PI) / 180, cs = cos(rad), sn = sin(rad), lab[3] = {l, c * cs, c * sn}, lin[3], cand[3];
    double low = 0, high = c;
    oklab_to_linear_srgb(lab, lin);
    if (in_gamut(lin)) {
        linear_to_rgb(lin, r, g, b);
        return;
    }
    lab[1] = lab[2] = 0;
    oklab_to_linear_srgb(lab, lin);
    for (int i = 0; i < 20; i++) {
        double mid = (low + high) / 2;
        lab[1] = mid * cs;
        lab[2] = mid * sn;
        oklab_to_linear_srgb(lab, cand);
        if (in_gamut(cand)) {
            low = mid;
            memcpy(lin, cand, sizeof lin);
        } else {
            high = mid;
        }
    }
    linear_to_rgb(lin, r, g, b);
}

/* ---- colour values -------------------------------------------------------- */

static int num(const char **p, double *out)
{
    char *e;
    double v;
    while (isspace((unsigned char)**p))
        (*p)++;
    if (!**p || (!isdigit((unsigned char)**p) && !strchr("+-.", **p)))
        return -1;
    v = strtod(*p, &e);
    if (e == *p)
        return -1;
    *out = v;
    *p = e;
    return 0;
}

/* "NAME(" ... ")" with the three arguments: 1 when s is that function. */
static int args3(const char *s, const char *fn, double v[3], int pct[3])
{
    size_t n = strlen(fn);
    const char *p;
    if (strncasecmp(s, fn, n) != 0 || s[n] != '(')
        return 0;
    p = s + n + 1;
    for (int i = 0; i < 3; i++) {
        pct[i] = 0;
        if (num(&p, &v[i]) != 0)
            return -1;
        if (i == 0 && strcasecmp(fn, "okhsl") == 0 && strncmp(p, "deg", 3) == 0)
            p += 3;
        if (i == 2 && strcasecmp(fn, "oklch") == 0 && strncmp(p, "deg", 3) == 0)
            p += 3;
        if (*p == '%') {
            pct[i] = 1;
            p++;
        }
        if (i < 2 && !isspace((unsigned char)*p))
            return -1;
    }
    while (isspace((unsigned char)*p))
        p++;
    return *p == ')' && p[1] == '\0' ? 1 : -1;
}

int tui_color_parse(const char *s, tui_color *out, char *err, size_t errcap)
{
    double v[3];
    int pct[3], rc, r, g, b;
    memset(out, 0, sizeof *out);
    if (!*s) {
        out->kind = TUI_COLOR_DEFAULT;
        return 0;
    }
    if (s[0] == '#' && (strlen(s) == 4 || strlen(s) == 7)) {
        int digits = (int)strlen(s) - 1, ok = 1;
        unsigned val[6];
        for (int i = 0; i < digits; i++) {
            char c = s[1 + i];
            if (!isxdigit((unsigned char)c))
                ok = 0;
            else
                val[i] = (unsigned)(c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10);
        }
        if (ok) {
            out->kind = TUI_COLOR_RGB;
            if (digits == 3) {
                out->r = (unsigned char)(val[0] * 17), out->g = (unsigned char)(val[1] * 17), out->b = (unsigned char)(val[2] * 17);
            } else {
                out->r = (unsigned char)(val[0] * 16 + val[1]), out->g = (unsigned char)(val[2] * 16 + val[3]);
                out->b = (unsigned char)(val[4] * 16 + val[5]);
            }
            return 0;
        }
    }
    if ((rc = args3(s, "oklch", v, pct)) == 1) {
        double l = pct[0] ? v[0] / 100 : v[0];
        if (l < 0 || l > 1 || v[1] < 0) {
            if (err && errcap)
                (void)snprintf(err, errcap, l < 0 || l > 1 ? "l must be between 0 and 1: %g" : "c must not be negative: %g",
                               l < 0 || l > 1 ? l : v[1]);
            return -1;
        }
        oklch_to_rgb(l, v[1], fmod(fmod(v[2], 360) + 360, 360), &r, &g, &b);
    } else if (rc == 0 && (rc = args3(s, "okhsl", v, pct)) == 1) {
        double sat = pct[1] ? v[1] / 100 : v[1], l = pct[2] ? v[2] / 100 : v[2];
        if (sat < 0 || sat > 1 || l < 0 || l > 1) {
            if (err && errcap)
                (void)snprintf(err, errcap, "%c must be between 0 and 1: %g", sat < 0 || sat > 1 ? 's' : 'l',
                               sat < 0 || sat > 1 ? sat : l);
            return -1;
        }
        tui_okhsl_to_rgb(v[0], sat, l, &r, &g, &b);
    } else {
        if (err && errcap)
            (void)snprintf(err, errcap, "Invalid color value: %s", s);
        return -1;
    }
    out->kind = TUI_COLOR_RGB;
    out->r = (unsigned char)r;
    out->g = (unsigned char)g;
    out->b = (unsigned char)b;
    return 0;
}

/* ---- theme files ---------------------------------------------------------- */

typedef struct {
    char *p;
    size_t n, cap;
} theme_msg;

static void msg_add(theme_msg *m, const char *fmt, ...) __attribute__((format(printf, 2, 3)));

static void msg_add(theme_msg *m, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    if (m->n + 1 < m->cap) {
        int w = vsnprintf(m->p + m->n, m->cap - m->n, fmt, ap);
        if (w > 0)
            m->n = (size_t)w < m->cap - m->n ? m->n + (size_t)w : m->cap - 1;
    }
    va_end(ap);
}

static int is_color_literal(const char *s)
{
    return !*s || s[0] == '#' || strncasecmp(s, "oklch(", 6) == 0 || strncasecmp(s, "okhsl(", 6) == 0;
}

/* A token value: a string (literal or variable) or an integer index, resolved through vars. 0 or -1 (err). */
static int resolve_value(const mj *vars, const mj *val, tui_color *out, char *err, size_t errcap)
{
    const mj *th_cur = val;
    int depth = 0;
    while (th_cur->kind == MJ_STR && !is_color_literal(th_cur->str)) {
        const mj *next = mj_get(vars, th_cur->str);
        if (!next) {
            (void)snprintf(err, errcap, "Variable reference not found: %s", th_cur->str);
            return -1;
        }
        if (++depth > 64) {
            (void)snprintf(err, errcap, "Circular variable reference detected: %s", th_cur->str);
            return -1;
        }
        th_cur = next;
    }
    if (th_cur->kind == MJ_NUM) {
        memset(out, 0, sizeof *out);
        out->kind = TUI_COLOR_INDEX;
        out->index = (int)th_cur->num;
        return 0;
    }
    return tui_color_parse(th_cur->str, out, err, errcap);
}

static int value_ok(const mj *v)
{
    return v->kind == MJ_STR || (v->kind == MJ_NUM && v->num >= 0 && v->num <= 255 && v->num == floor(v->num));
}

int tui_theme_parse(const char *json, size_t n, const char *label, tui_theme *out, char *err, size_t errcap)
{
    char perr[160];
    mj *root = mj_parse(json, n, perr, sizeof perr);
    const mj *colors, *vars, *x, *name;
    int seen[TUI_T_N] = {0};
    int bad = 0, missing = 0;
    char other[2048], miss[2048];
    theme_msg om = {other, 0, sizeof other}, mm = {miss, 0, sizeof miss};
    if (err && errcap)
        err[0] = '\0';
    if (!root) {
        if (err && errcap)
            (void)snprintf(err, errcap, "Failed to parse theme %s: %s", label, perr);
        return -1;
    }
    other[0] = miss[0] = '\0';
    memset(out, 0, sizeof *out);
    out->appearance = -1;
    if (root->kind != MJ_OBJ) {
        if (err && errcap)
            (void)snprintf(err, errcap, "Invalid theme \"%s\": expected an object with a \"colors\" map.", label);
        mj_free(root);
        return -1;
    }
    name = mj_get(root, "name");
    if (name && name->kind == MJ_STR && strchr(name->str, '/')) {
        if (err && errcap)
            (void)snprintf(err, errcap,
                           "Invalid theme name \"%s\": theme names cannot contain \"/\" because it is reserved for automatic light/dark theme settings.",
                           name->str);
        mj_free(root);
        return -1;
    }
    for (size_t i = 0; i < root->n; i++) {
        const char *k = root->keys[i];
        if (strcmp(k, "$schema") && strcmp(k, "name") && strcmp(k, "appearance") && strcmp(k, "vars") && strcmp(k, "colors") &&
            strcmp(k, "export")) {
            msg_add(&om, "  - /%s: must not have additional properties\n", k), bad = 1;
        }
    }
    if (!name || name->kind != MJ_STR || !*name->str) {
        msg_add(&om, "  - /name: must be a non-empty string\n"), bad = 1;
    } else {
        (void)snprintf(out->name, sizeof out->name, "%s", name->str);
    }
    if ((x = mj_get(root, "appearance"))) {
        if (x->kind == MJ_STR && strcmp(x->str, "dark") == 0)
            out->appearance = 0;
        else if (x->kind == MJ_STR && strcmp(x->str, "light") == 0)
            out->appearance = 1;
        else
            msg_add(&om, "  - /appearance: must be \"dark\" or \"light\"\n"), bad = 1;
    }
    vars = mj_get(root, "vars");
    if (vars) {
        if (vars->kind != MJ_OBJ) {
            msg_add(&om, "  - /vars: must be an object\n"), bad = 1;
            vars = NULL;
        } else {
            for (size_t i = 0; i < vars->n; i++)
                if (!value_ok(vars->kids[i]))
                    msg_add(&om, "  - /vars/%s: must be a string or an integer from 0 to 255\n", vars->keys[i]), bad = 1;
        }
    }
    if ((x = mj_get(root, "export"))) {
        if (x->kind != MJ_OBJ) {
            msg_add(&om, "  - /export: must be an object\n"), bad = 1;
        } else {
            for (size_t i = 0; i < x->n; i++) {
                const char *k = x->keys[i];
                if (strcmp(k, "pageBg") && strcmp(k, "cardBg") && strcmp(k, "infoBg"))
                    msg_add(&om, "  - /export: must not have additional properties (%s)\n", k), bad = 1;
                else if (!value_ok(x->kids[i]))
                    msg_add(&om, "  - /export/%s: must be a string or an integer from 0 to 255\n", k), bad = 1;
            }
        }
    }
    colors = mj_get(root, "colors");
    if (!colors || colors->kind != MJ_OBJ) {
        msg_add(&om, "  - /colors: must be an object\n"), bad = 1;
    } else {
        for (size_t i = 0; i < colors->n; i++) {
            int t = tui_token_index(colors->keys[i]);
            char e[200];
            if (t < 0) {
                msg_add(&om, "  - /colors: must not have additional properties (%s)\n", colors->keys[i]), bad = 1;
            } else if (!value_ok(colors->kids[i])) {
                msg_add(&om, "  - /colors/%s: must be a string or an integer from 0 to 255\n", colors->keys[i]), bad = 1;
            } else if (resolve_value(vars, colors->kids[i], &out->c[t], e, sizeof e) != 0) {
                msg_add(&om, "  - /colors/%s: %s\n", colors->keys[i], e), bad = 1;
            } else {
                seen[t] = 1;
            }
        }
        for (int t = 0; t < TUI_T_N; t++) {
            if (!seen[t] && !optional_token(t) && !mj_get(colors, token_names[t])) {
                msg_add(&mm, "  - %s\n", token_names[t]);
                missing = 1;
            }
        }
    }
    if (bad || missing) {
        if (err && errcap) {
            theme_msg e = {err, 0, errcap};
            msg_add(&e, "Invalid theme \"%s\":\n", label);
            if (missing)
                msg_add(&e, "\nMissing required color tokens:\n%s\nPlease add these colors to your theme's \"colors\" object.\n"
                            "See the built-in themes (dark.json, light.json) for reference values.",
                        miss);
            if (bad)
                msg_add(&e, "%s\nOther errors:\n%s", missing ? "\n" : "", other);
            while (e.n > 0 && err[e.n - 1] == '\n')
                err[--e.n] = '\0';
        }
        mj_free(root);
        return -1;
    }
    for (size_t i = 0; i < sizeof fallbacks / sizeof fallbacks[0]; i++)
        if (!seen[fallbacks[i].token])
            out->c[fallbacks[i].token] = out->c[fallbacks[i].fallback];
    mj_free(root);
    return 0;
}

static const char builtin_dark[] =
#include "theme_dark.inc"
    ;
static const char builtin_light[] =
#include "theme_light.inc"
    ;

int tui_theme_builtin(const char *name, tui_theme *out)
{
    const char *src = strcmp(name, "dark") == 0 ? builtin_dark : strcmp(name, "light") == 0 ? builtin_light : NULL;
    char err[256];
    if (!src || tui_theme_parse(src, strlen(src), name, out, err, sizeof err) != 0)
        return -1;
    return 0;
}

/* ---- the current theme and its escape sequences --------------------------- */

static tui_theme th_cur;
static int explicit_theme, cur_valid, cur_true;
static char fg_sgr[TUI_T_N][24], bg_sgr[TUI_T_N][24];
static int built_for = -1; /* the (light, truecolor) key an implicit theme was built for */

static const int CUBE[6] = {0, 95, 135, 175, 215, 255};

static int closest(const int *vals, int n, int target)
{
    int best = 0, bd = 1 << 30;
    for (int i = 0; i < n; i++) {
        int d = abs(target - vals[i]);
        if (d < bd) {
            bd = d;
            best = i;
        }
    }
    return best;
}

static double cdist(int r1, int g1, int b1, int r2, int g2, int b2)
{
    double dr = r1 - r2, dg = g1 - g2, db = b1 - b2;
    return dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114;
}

int tui_rgb_to_256(int r, int g, int b)
{
    int gray_vals[24], ri = closest(CUBE, 6, r), gi = closest(CUBE, 6, g), bi = closest(CUBE, 6, b);
    int cube_index = 16 + 36 * ri + 6 * gi + bi, gray, go, gv, mx, mn;
    for (int i = 0; i < 24; i++)
        gray_vals[i] = 8 + i * 10;
    gray = js_round(0.299 * r + 0.587 * g + 0.114 * b);
    go = closest(gray_vals, 24, gray);
    gv = gray_vals[go];
    mx = r > g ? (r > b ? r : b) : (g > b ? g : b);
    mn = r < g ? (r < b ? r : b) : (g < b ? g : b);
    if (mx - mn < 10 && cdist(r, g, b, gv, gv, gv) < cdist(r, g, b, CUBE[ri], CUBE[gi], CUBE[bi]))
        return 232 + go;
    return cube_index;
}

static void sgr(char *out, size_t cap, const tui_color *c, int truecolor, int bg)
{
    switch (c->kind) {
    case TUI_COLOR_DEFAULT: (void)snprintf(out, cap, "\x1b[%dm", bg ? 49 : 39); break;
    case TUI_COLOR_INDEX: (void)snprintf(out, cap, "\x1b[%d;5;%dm", bg ? 48 : 38, c->index); break;
    default:
        if (truecolor)
            (void)snprintf(out, cap, "\x1b[%d;2;%d;%d;%dm", bg ? 48 : 38, c->r, c->g, c->b);
        else
            (void)snprintf(out, cap, "\x1b[%d;5;%dm", bg ? 48 : 38, tui_rgb_to_256(c->r, c->g, c->b));
    }
}

static void rebuild(int truecolor)
{
    for (int i = 0; i < TUI_T_N; i++) {
        sgr(fg_sgr[i], sizeof fg_sgr[i], &th_cur.c[i], truecolor, 0);
        sgr(bg_sgr[i], sizeof bg_sgr[i], &th_cur.c[i], truecolor, 1);
    }
    cur_true = truecolor;
    cur_valid = 1;
}

static int answered_light = -1; /* tui_terminal_light_set */

void tui_terminal_light_set(int light)
{
    answered_light = light < 0 ? -1 : light != 0;
}

int tui_terminal_light(const char *colorfgbg)
{
    const char *v = colorfgbg ? colorfgbg : getenv("COLORFGBG"), *semi, *p;
    long idx = 0;
    if (!colorfgbg && answered_light >= 0)
        return answered_light;
    if (!v)
        return 0;
    semi = strrchr(v, ';');
    p = semi ? semi + 1 : v;
    while (*p == ' ')
        p++;
    if (!isdigit((unsigned char)*p))
        return 0;
    for (const char *q = p; *q && *q != ' '; q++) {
        if (!isdigit((unsigned char)*q) || q - p >= 2)
            return 0;
        idx = idx * 10 + (*q - '0');
    }
    return idx <= 15 && !(idx <= 6 || idx == 8);
}

int tui_terminal_truecolor(void)
{
    const char *c = getenv("COLORTERM");
    return c && (strstr(c, "truecolor") || strstr(c, "24bit"));
}

void tui_theme_use(const tui_theme *t, int truecolor)
{
    th_cur = *t;
    explicit_theme = 1;
    rebuild(truecolor);
}

void tui_theme_follow_env(void)
{
    explicit_theme = 0;
    built_for = -1;
}

static void ensure(void)
{
    if (explicit_theme)
        return;
    int key = tui_terminal_light(NULL) * 2 + tui_terminal_truecolor();
    if (key != built_for) {
        if (tui_theme_builtin(key & 2 ? "light" : "dark", &th_cur) != 0)
            memset(&th_cur, 0, sizeof th_cur);
        rebuild(key & 1);
        built_for = key;
    }
}

const tui_theme *tui_theme_current(void)
{
    ensure();
    return &th_cur;
}

const char *tui_fg(tui_token t)
{
    ensure();
    return (int)t >= 0 && t < TUI_T_N ? fg_sgr[t] : "";
}

const char *tui_bg(tui_token t)
{
    ensure();
    return (int)t >= 0 && t < TUI_T_N ? bg_sgr[t] : "";
}

tui_token tui_thinking_token(const char *level)
{
    static const struct {
        const char *name;
        tui_token t;
    } m[] = {{"minimal", TUI_T_THINKING_MINIMAL}, {"low", TUI_T_THINKING_LOW},     {"medium", TUI_T_THINKING_MEDIUM},
             {"high", TUI_T_THINKING_HIGH},       {"xhigh", TUI_T_THINKING_XHIGH}, {"max", TUI_T_THINKING_MAX}};
    for (size_t i = 0; level && i < sizeof m / sizeof m[0]; i++)
        if (strcmp(level, m[i].name) == 0)
            return m[i].t;
    return TUI_T_THINKING_OFF;
}

void tui_hl_theme_current(tui_hl_theme *out)
{
    out->sgr[TUI_HL_COMMENT] = tui_fg(TUI_T_SYNTAX_COMMENT);
    out->sgr[TUI_HL_KEYWORD] = tui_fg(TUI_T_SYNTAX_KEYWORD);
    out->sgr[TUI_HL_FUNCTION] = tui_fg(TUI_T_SYNTAX_FUNCTION);
    out->sgr[TUI_HL_VARIABLE] = tui_fg(TUI_T_SYNTAX_VARIABLE);
    out->sgr[TUI_HL_STRING] = tui_fg(TUI_T_SYNTAX_STRING);
    out->sgr[TUI_HL_NUMBER] = tui_fg(TUI_T_SYNTAX_NUMBER);
    out->sgr[TUI_HL_TYPE] = tui_fg(TUI_T_SYNTAX_TYPE);
    out->sgr[TUI_HL_OPERATOR] = tui_fg(TUI_T_SYNTAX_OPERATOR);
    out->sgr[TUI_HL_PUNCT] = tui_fg(TUI_T_SYNTAX_PUNCTUATION);
    out->sgr[TUI_HL_ADD] = tui_fg(TUI_T_TOOL_DIFF_ADDED);
    out->sgr[TUI_HL_DEL] = tui_fg(TUI_T_TOOL_DIFF_REMOVED);
    out->sgr[TUI_HL_META] = tui_fg(TUI_T_TOOL_DIFF_CONTEXT);
}