Skip to content
pi-c Artifact [caae09973f]
Login

Artifact [caae09973f]

Artifact caae09973f5507999bb2cf0786c295e99e01eb0cb727901ea192958736e12014:


/* 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 LINEAR_SRGB_TO_LMS[3][3] = {
    {0.4122214694707629, 0.5363325372617349, 0.0514459932675022},
    {0.2119034958178251, 0.6806995506452344, 0.1073969535369405},
    {0.0883024591900564, 0.2817188391361215, 0.6299787016738222},
};
static const double LMS_TO_LAB[3][3] = {
    {0.210454268309314, 0.793617774702305, -0.0040720430116193},
    {1.9779985324311684, -2.42859224204858, 0.450593709617411},
    {0.0259040424655478, 0.7827717124575296, -0.8086757549230774},
};
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 th_oklab_to_okhsl_l(double x)
{
    double d = K3 * x - K1;
    double disc = d * d + 4.0 * K2 * K3 * x;
    if (disc < 0.0)
        disc = 0.0;
    return 0.5 * (d + sqrt(disc));
}

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

static double th_srgb_to_linear(double v)
{
    return v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4);
}

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);
}

static void th_rgb_to_oklab(tui_rgb c, double lab[3])
{
    double lin[3] = {th_srgb_to_linear(c.r / 255.0), th_srgb_to_linear(c.g / 255.0), th_srgb_to_linear(c.b / 255.0)};
    double lms[3];
    mul(LINEAR_SRGB_TO_LMS, lin, lms);
    for (int i = 0; i < 3; i++)
        lms[i] = cbrt(lms[i]);
    mul(LMS_TO_LAB, lms, lab);
}

static double th_oklab_lightness(tui_rgb c)
{
    double lab[3];
    th_rgb_to_oklab(c, lab);
    return lab[0];
}

static void th_rgb_to_oklch(tui_rgb c, double *l, double *ch, double *h)
{
    double lab[3];
    th_rgb_to_oklab(c, lab);
    *l = lab[0];
    *ch = hypot(lab[1], lab[2]);
    *h = *ch < 1e-9 ? 0.0 : fmod(atan2(lab[2], lab[1]) * 180.0 / M_PI + 360.0, 360.0);
}

/* 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 = isfinite(lin[i]) ? linear_to_srgb(lin[i]) : 0.0;
        v = !isfinite(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 cl = !isfinite(l) || l < 0.0 ? 0.0 : l > 1.0 ? 1.0 : l;
    double cs = !isfinite(s) || s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s;
    double L = okhsl_to_oklab_l(cl), lab[3] = {L, 0, 0}, lin[3];
    if (L > 1e-9 && L < 1.0 - 1e-9 && cs > 0 && isfinite(h)) {
        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 (cs < 0.8) {
            double t = 1.25 * cs, k1 = 0.8 * st[0];
            double denom = st[1] > 1e-12 ? 1 - (1 - k1 / st[1]) * t : 1.0;
            chroma = fabs(denom) > 1e-12 ? (t * k1) / denom : 0.0;
        } else {
            double t = 5 * (cs - 0.8);
            double span = st[2] - st[1];
            if (st[0] > 1e-12 && span > 1e-12) {
                double k1 = (0.2 * pow(st[1], 2) * pow(1.25, 2)) / st[0];
                double denom = 1 - (1 - k1 / span) * t;
                chroma = fabs(denom) > 1e-12 ? st[1] + (t * k1) / denom : st[2];
            } else {
                chroma = st[1];
            }
        }
        lab[1] = chroma * a;
        lab[2] = chroma * bb;
    }
    oklab_to_linear_srgb(lab, lin);
    linear_to_rgb(lin, r, g, b);
}

static void th_rgb_to_okhsl(tui_rgb c, double *h, double *s, double *l)
{
    double lab[3];
    th_rgb_to_oklab(c, lab);
    double chroma = hypot(lab[1], lab[2]);
    double lightness = th_oklab_to_okhsl_l(lab[0]);
    if (chroma < 1e-9 || lightness <= 0.0 || lightness >= 1.0 || lab[0] <= 1e-9 || lab[0] >= 1.0 - 1e-9) {
        *h = 0.0;
        *s = 0.0;
        *l = lightness < 0.0 ? 0.0 : lightness > 1.0 ? 1.0 : lightness;
        return;
    }
    double hue = fmod(atan2(lab[2], lab[1]) * 180.0 / M_PI + 360.0, 360.0);
    double st[3];
    chroma_stops(lab[0], lab[1] / chroma, lab[2] / chroma, st);
    double c0 = st[0], cmid = st[1], cmax = st[2], sat;
    if (chroma < cmid) {
        double k1 = 0.8 * c0;
        double denom = cmid > 1e-12 ? k1 + (1.0 - k1 / cmid) * chroma : k1;
        sat = denom > 1e-12 ? 0.8 * (chroma / denom) : 0.0;
    } else {
        double k1 = c0 > 1e-12 ? (0.2 * cmid * cmid * 1.25 * 1.25) / c0 : 1.0;
        double offset = chroma - cmid;
        double span = cmax - cmid;
        double denom = span > 1e-12 ? k1 + (1.0 - k1 / span) * offset : k1;
        sat = denom > 1e-12 ? 0.8 + 0.2 * (offset / denom) : 1.0;
    }
    *h = hue;
    *s = sat < 0.0 ? 0.0 : sat > 1.0 ? 1.0 : sat;
    *l = lightness;
}

/* 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;
}

/* ---- generated terminal-palette system theme (Pi's system-theme.ts) ------- */

enum {
    SYS_FAM_NEUTRAL,
    SYS_FAM_BLUE,
    SYS_FAM_GREEN,
    SYS_FAM_RED,
    SYS_FAM_YELLOW,
    SYS_FAM_ORANGE,
    SYS_FAM_VIOLET,
    SYS_FAM_CALAMINE,
    SYS_FAM_THINKING_SLATE,
    SYS_FAM_THINKING_BLUE,
    SYS_FAM_THINKING_PERIWINKLE,
    SYS_FAM_THINKING_VIOLET,
    SYS_FAM_THINKING_MAGENTA,
    SYS_FAM_THINKING_RED,
    SYS_FAM_N
};

typedef struct {
    double hue;
    double sat_min;
    double sat_max;
    int slot;
} sys_family;

static const sys_family sys_families[SYS_FAM_N] = {
    [SYS_FAM_NEUTRAL] = {231.49, 0.02, 0.08, 8},
    [SYS_FAM_BLUE] = {231.49, 0.1, 0.68, 4},
    [SYS_FAM_GREEN] = {158.68, 0.1, 0.76, 2},
    [SYS_FAM_RED] = {20.0, 0.1, 0.92, 1},
    [SYS_FAM_YELLOW] = {82.36, 0.5, 1.0, 3},
    [SYS_FAM_ORANGE] = {52.0, 0.12, 0.85, 3},
    [SYS_FAM_VIOLET] = {295.0, 0.2, 0.6, 5},
    [SYS_FAM_CALAMINE] = {202.43, 0.1, 0.74, 6},
    [SYS_FAM_THINKING_SLATE] = {231.49, 0.08, 0.2, 4},
    [SYS_FAM_THINKING_BLUE] = {231.49, 0.2, 0.45, 4},
    [SYS_FAM_THINKING_PERIWINKLE] = {263.25, 0.3, 0.6, 6},
    [SYS_FAM_THINKING_VIOLET] = {295.0, 0.4, 0.75, 5},
    [SYS_FAM_THINKING_MAGENTA] = {337.5, 0.5, 0.85, 13},
    [SYS_FAM_THINKING_RED] = {20.0, 0.95, 1.0, 1},
};

static const unsigned char sys_token_family[TUI_T_N] = {
    [TUI_T_ACCENT] = SYS_FAM_VIOLET,
    [TUI_T_BORDER] = SYS_FAM_BLUE,
    [TUI_T_BORDER_ACCENT] = SYS_FAM_VIOLET,
    [TUI_T_BORDER_MUTED] = SYS_FAM_NEUTRAL,
    [TUI_T_SUCCESS] = SYS_FAM_GREEN,
    [TUI_T_ERROR] = SYS_FAM_RED,
    [TUI_T_WARNING] = SYS_FAM_YELLOW,
    [TUI_T_MUTED] = SYS_FAM_NEUTRAL,
    [TUI_T_DIM] = SYS_FAM_NEUTRAL,
    [TUI_T_TEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_THINKING_TEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_SCROLLBAR_TRACK] = SYS_FAM_NEUTRAL,
    [TUI_T_SCROLLBAR_THUMB] = SYS_FAM_NEUTRAL,
    [TUI_T_SELECTED_BG] = SYS_FAM_BLUE,
    [TUI_T_SEARCH_MATCH_BG] = SYS_FAM_ORANGE,
    [TUI_T_SEARCH_MATCH_TEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_USER_MESSAGE_BG] = SYS_FAM_BLUE,
    [TUI_T_USER_MESSAGE_TEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_CUSTOM_MESSAGE_BG] = SYS_FAM_VIOLET,
    [TUI_T_CUSTOM_MESSAGE_TEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_CUSTOM_MESSAGE_LABEL] = SYS_FAM_VIOLET,
    [TUI_T_TOOL_PENDING_BG] = SYS_FAM_NEUTRAL,
    [TUI_T_TOOL_SUCCESS_BG] = SYS_FAM_GREEN,
    [TUI_T_TOOL_ERROR_BG] = SYS_FAM_RED,
    [TUI_T_TOOL_TITLE] = SYS_FAM_NEUTRAL,
    [TUI_T_TOOL_OUTPUT] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_HEADING] = SYS_FAM_YELLOW,
    [TUI_T_MD_LINK] = SYS_FAM_BLUE,
    [TUI_T_MD_LINK_URL] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_CODE] = SYS_FAM_VIOLET,
    [TUI_T_MD_CODE_BLOCK] = SYS_FAM_GREEN,
    [TUI_T_MD_CODE_BLOCK_BORDER] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_QUOTE] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_QUOTE_BORDER] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_HR] = SYS_FAM_NEUTRAL,
    [TUI_T_MD_LIST_BULLET] = SYS_FAM_VIOLET,
    [TUI_T_TOOL_DIFF_ADDED] = SYS_FAM_GREEN,
    [TUI_T_TOOL_DIFF_REMOVED] = SYS_FAM_RED,
    [TUI_T_TOOL_DIFF_CONTEXT] = SYS_FAM_NEUTRAL,
    [TUI_T_SYNTAX_COMMENT] = SYS_FAM_NEUTRAL,
    [TUI_T_SYNTAX_KEYWORD] = SYS_FAM_BLUE,
    [TUI_T_SYNTAX_FUNCTION] = SYS_FAM_YELLOW,
    [TUI_T_SYNTAX_VARIABLE] = SYS_FAM_CALAMINE,
    [TUI_T_SYNTAX_STRING] = SYS_FAM_ORANGE,
    [TUI_T_SYNTAX_NUMBER] = SYS_FAM_GREEN,
    [TUI_T_SYNTAX_TYPE] = SYS_FAM_VIOLET,
    [TUI_T_SYNTAX_OPERATOR] = SYS_FAM_NEUTRAL,
    [TUI_T_SYNTAX_PUNCTUATION] = SYS_FAM_NEUTRAL,
    [TUI_T_THINKING_OFF] = SYS_FAM_NEUTRAL,
    [TUI_T_THINKING_MINIMAL] = SYS_FAM_THINKING_SLATE,
    [TUI_T_THINKING_LOW] = SYS_FAM_THINKING_BLUE,
    [TUI_T_THINKING_MEDIUM] = SYS_FAM_THINKING_PERIWINKLE,
    [TUI_T_THINKING_HIGH] = SYS_FAM_THINKING_VIOLET,
    [TUI_T_THINKING_XHIGH] = SYS_FAM_THINKING_MAGENTA,
    [TUI_T_THINKING_MAX] = SYS_FAM_THINKING_RED,
    [TUI_T_BASH_MODE] = SYS_FAM_GREEN,
};

enum {
    SYS_LVL_PANEL,
    SYS_LVL_TRACK,
    SYS_LVL_THINKING0,
    SYS_LVL_THINKING1,
    SYS_LVL_THINKING2,
    SYS_LVL_THINKING3,
    SYS_LVL_THINKING4,
    SYS_LVL_THINKING5,
    SYS_LVL_THINKING6,
    SYS_LVL_SUBTLE,
    SYS_LVL_THUMB,
    SYS_LVL_READABLE,
    SYS_LVL_EMPHASIS,
    SYS_LVL_TEXT_ON_PANEL,
    SYS_LVL_TEXT,
    SYS_LVL_N
};

typedef struct {
    double c[6];
    double lo, hi;
} sys_curve;

/* [level][0 = dark, 1 = light] */
static const sys_curve sys_levels[SYS_LVL_N][2] = {
    [SYS_LVL_PANEL] = {
        {{0.29131, -0.39746, 2.33185, -0.85524, -1.2076, 0.86276}, 0.0, 0.979},
        {{-3.74073, 27.94549, -78.44258, 112.6798, -79.60015, 22.11277}, 0.348, 1.0},
    },
    [SYS_LVL_TRACK] = {
        {{0.39028, -0.23015, 0.83573, 2.43829, -4.38292, 2.01582}, 0.0, 0.946},
        {{-5.24921, 38.37322, -107.28833, 152.10005, -106.17127, 29.18061}, 0.368, 1.0},
    },
    [SYS_LVL_THINKING0] = {
        {{0.52988, -0.05809, -0.30924, 4.63567, -6.52933, 2.89108}, 0.0, 0.873},
        {{-28.27749, 182.85284, -469.62416, 603.15916, -384.59976, 97.35147}, 0.51, 1.0},
    },
    [SYS_LVL_THINKING1] = {
        {{0.55278, -0.03667, -0.45659, 4.95347, -6.90265, 3.0706}, 0.0, 0.858},
        {{-37.10484, 235.86282, -596.62344, 754.3633, -474.00763, 118.3551}, 0.535, 1.0},
    },
    [SYS_LVL_THINKING2] = {
        {{0.57486, -0.01765, -0.58987, 5.25227, -7.27175, 3.25532}, 0.0, 0.842},
        {{-59.89653, 377.05024, -945.07843, 1182.03145, -734.96375, 181.68658}, 0.556, 1.0},
    },
    [SYS_LVL_THINKING3] = {
        {{0.59621, -0.00062, -0.71148, 5.53588, -7.6392, 3.44606}, 0.0, 0.827},
        {{-72.07122, 445.84082, -1099.57352, 1353.88793, -829.53392, 202.26164}, 0.58, 1.0},
    },
    [SYS_LVL_THINKING4] = {
        {{0.61691, 0.01462, -0.82288, 5.80651, -8.00641, 3.64333}, 0.0, 0.811},
        {{-110.14338, 674.21488, -1645.75941, 2004.32367, -1215.15899, 293.3183}, 0.6, 1.0},
    },
    [SYS_LVL_THINKING5] = {
        {{0.63702, 0.02826, -0.92498, 6.06465, -8.37246, 3.84651}, 0.0, 0.795},
        {{-175.47701, 1063.54495, -2570.70594, 3098.80776, -1860.15527, 444.76392}, 0.62, 1.0},
    },
    [SYS_LVL_THINKING6] = {
        {{0.65658, 0.04044, -1.01835, 6.30989, -8.73529, 4.05439}, 0.0, 0.779},
        {{-183.81712, 1094.70055, -2602.68539, 3088.71276, -1826.91131, 430.75931}, 0.643, 1.0},
    },
    [SYS_LVL_SUBTLE] = {
        {{0.56762, -0.02475, -0.5383, 5.12628, -7.10931, 3.17324}, 0.0, 0.848},
        {{-232.85459, 1376.54473, -3249.11801, 3827.91186, -2248.29472, 526.55751}, 0.657, 1.0},
    },
    [SYS_LVL_THUMB] = {
        {{0.60323, 0.00278, -0.73328, 5.57157, -7.68067, 3.46933}, 0.0, 0.823},
        {{-82.89897, 511.01355, -1255.98095, 1540.76821, -940.68087, 228.58523}, 0.586, 1.0},
    },
    [SYS_LVL_READABLE] = {
        {{0.66937, 0.04704, -1.06871, 6.43941, -8.9332, 4.17229}, 0.0, 0.77},
        {{-1554.52576, 8733.56817, -19604.93507, 21977.72696, -12300.99599, 2749.81288}, 0.751, 1.0},
    },
    [SYS_LVL_EMPHASIS] = {
        {{0.7303, 0.07695, -1.31626, 7.1681, -10.14436, 4.92846}, 0.0, 0.712},
        {{-4948.31942, 26870.91986, -58334.48399, 63280.17197, -34298.01053, 7430.30146}, 0.811, 1.0},
    },
    [SYS_LVL_TEXT_ON_PANEL] = {
        {{0.86713, 0.05232, -0.89428, 4.79014, -5.5432, 1.75023}, 0.0, 0.542},
        {{-8570.89457, 43954.60805, -90084.00702, 92220.6791, -47152.15802, 9632.27113}, 0.867, 1.0},
    },
    [SYS_LVL_TEXT] = {
        {{0.89242, 0.02311, -0.44862, 2.34417, -0.06084, -2.63844}, 0.0, 0.5},
        {{-2004.67048, 6664.47299, -6060.70202, -1792.61209, 5133.82359, -1939.85583}, 0.894, 1.0},
    },
};

#define SYS_BG (-1)
#define SYS_ON_BG 1, {SYS_BG}
#define SYS_ON_TOOL 3, {TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}
#define SYS_ON_BG_TOOL 4, {SYS_BG, TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}
#define SYS_ON_BG_SEL_TOOL 5, {SYS_BG, TUI_T_SELECTED_BG, TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}
#define SYS_ON_BG_SEL_CUST_TOOL \
    6, {SYS_BG, TUI_T_SELECTED_BG, TUI_T_CUSTOM_MESSAGE_BG, TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}
#define SYS_ON_CUST_TOOL 4, {TUI_T_CUSTOM_MESSAGE_BG, TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}
#define SYS_ON_BG_MSG 3, {SYS_BG, TUI_T_USER_MESSAGE_BG, TUI_T_CUSTOM_MESSAGE_BG}
#define SYS_ON_BG_MSG_TOOL \
    6, {SYS_BG, TUI_T_USER_MESSAGE_BG, TUI_T_CUSTOM_MESSAGE_BG, TUI_T_TOOL_PENDING_BG, TUI_T_TOOL_SUCCESS_BG, TUI_T_TOOL_ERROR_BG}

typedef struct {
    tui_token token;
    int level;
    int n_on;
    int on[6];
} sys_rule;

static const sys_rule sys_rules[] = {
    {TUI_T_USER_MESSAGE_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_TOOL_PENDING_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_TOOL_SUCCESS_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_TOOL_ERROR_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_SELECTED_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_SEARCH_MATCH_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_CUSTOM_MESSAGE_BG, SYS_LVL_PANEL, SYS_ON_BG},
    {TUI_T_TEXT, SYS_LVL_TEXT, SYS_ON_BG},
    {TUI_T_TEXT, SYS_LVL_TEXT_ON_PANEL, 1, {TUI_T_SELECTED_BG}},
    {TUI_T_USER_MESSAGE_TEXT, SYS_LVL_TEXT_ON_PANEL, 1, {TUI_T_USER_MESSAGE_BG}},
    {TUI_T_TOOL_TITLE, SYS_LVL_TEXT_ON_PANEL, SYS_ON_TOOL},
    {TUI_T_ACCENT, SYS_LVL_READABLE, SYS_ON_BG_SEL_TOOL},
    {TUI_T_SUCCESS, SYS_LVL_READABLE, SYS_ON_BG_SEL_TOOL},
    {TUI_T_ERROR, SYS_LVL_READABLE, SYS_ON_BG_SEL_TOOL},
    {TUI_T_WARNING, SYS_LVL_READABLE, SYS_ON_BG_SEL_TOOL},
    {TUI_T_MUTED, SYS_LVL_READABLE, SYS_ON_BG_SEL_CUST_TOOL},
    {TUI_T_DIM, SYS_LVL_SUBTLE, SYS_ON_BG_SEL_CUST_TOOL},
    {TUI_T_THINKING_TEXT, SYS_LVL_READABLE, SYS_ON_BG},
    {TUI_T_CUSTOM_MESSAGE_TEXT, SYS_LVL_READABLE, SYS_ON_CUST_TOOL},
    {TUI_T_CUSTOM_MESSAGE_LABEL, SYS_LVL_READABLE, SYS_ON_BG_SEL_CUST_TOOL},
    {TUI_T_TOOL_OUTPUT, SYS_LVL_READABLE, SYS_ON_BG_TOOL},
    {TUI_T_MD_HEADING, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_LINK, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_LINK_URL, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_CODE, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_QUOTE, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_CODE_BLOCK_BORDER, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_LIST_BULLET, SYS_LVL_READABLE, SYS_ON_BG_MSG},
    {TUI_T_MD_CODE_BLOCK, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_TOOL_DIFF_ADDED, SYS_LVL_READABLE, SYS_ON_BG_TOOL},
    {TUI_T_TOOL_DIFF_REMOVED, SYS_LVL_READABLE, SYS_ON_BG_TOOL},
    {TUI_T_TOOL_DIFF_CONTEXT, SYS_LVL_READABLE, SYS_ON_BG_TOOL},
    {TUI_T_SYNTAX_COMMENT, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_KEYWORD, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_FUNCTION, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_VARIABLE, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_STRING, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_NUMBER, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_TYPE, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_OPERATOR, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SYNTAX_PUNCTUATION, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SEARCH_MATCH_TEXT, SYS_LVL_READABLE, 1, {TUI_T_SEARCH_MATCH_BG}},
    {TUI_T_BASH_MODE, SYS_LVL_READABLE, SYS_ON_BG},
    {TUI_T_BORDER, SYS_LVL_READABLE, SYS_ON_BG},
    {TUI_T_BORDER_ACCENT, SYS_LVL_READABLE, SYS_ON_BG},
    {TUI_T_BORDER_MUTED, SYS_LVL_SUBTLE, SYS_ON_BG},
    {TUI_T_MD_QUOTE_BORDER, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_MD_HR, SYS_LVL_READABLE, SYS_ON_BG_MSG_TOOL},
    {TUI_T_SCROLLBAR_TRACK, SYS_LVL_TRACK, SYS_ON_BG},
    {TUI_T_SCROLLBAR_THUMB, SYS_LVL_THUMB, 1, {TUI_T_SCROLLBAR_TRACK}},
    {TUI_T_THINKING_OFF, SYS_LVL_THINKING0, SYS_ON_BG},
    {TUI_T_THINKING_MINIMAL, SYS_LVL_THINKING1, SYS_ON_BG},
    {TUI_T_THINKING_LOW, SYS_LVL_THINKING2, SYS_ON_BG},
    {TUI_T_THINKING_MEDIUM, SYS_LVL_THINKING3, SYS_ON_BG},
    {TUI_T_THINKING_HIGH, SYS_LVL_THINKING4, SYS_ON_BG},
    {TUI_T_THINKING_XHIGH, SYS_LVL_THINKING5, SYS_ON_BG},
    {TUI_T_THINKING_MAX, SYS_LVL_THINKING6, SYS_ON_BG},
};

static int sys_is_panel(tui_token tok)
{
    switch (tok) {
    case TUI_T_USER_MESSAGE_BG:
    case TUI_T_TOOL_PENDING_BG:
    case TUI_T_TOOL_SUCCESS_BG:
    case TUI_T_TOOL_ERROR_BG:
    case TUI_T_SELECTED_BG:
    case TUI_T_SEARCH_MATCH_BG:
    case TUI_T_CUSTOM_MESSAGE_BG: return 1;
    default: return 0;
    }
}

static int sys_token_slot(tui_token tok)
{
    if (tok == TUI_T_SYNTAX_STRING)
        return 2;
    if (tok == TUI_T_SYNTAX_NUMBER)
        return 5;
    if (tok == TUI_T_SEARCH_MATCH_BG)
        return 3;
    return sys_families[sys_token_family[tok]].slot;
}

static double sys_rel_lum(tui_rgb c)
{
    return 0.2126 * th_srgb_to_linear(c.r / 255.0) + 0.7152 * th_srgb_to_linear(c.g / 255.0) +
           0.0722 * th_srgb_to_linear(c.b / 255.0);
}

double tui_wcag_contrast(tui_rgb a, tui_rgb b)
{
    double la = sys_rel_lum(a), lb = sys_rel_lum(b);
    double hi = la > lb ? la : lb, lo = la < lb ? la : lb;
    return (hi + 0.05) / (lo + 0.05);
}

static int sys_appearance(tui_rgb bg, int has_fg, tui_rgb fg)
{
    tui_rgb white = {255, 255, 255}, black = {0, 0, 0};
    double wc = tui_wcag_contrast(white, bg);
    double bc = tui_wcag_contrast(black, bg);
    if (has_fg) {
        double fg_l = th_oklab_lightness(fg);
        double bg_l = th_oklab_lightness(bg);
        if (fabs(fg_l - bg_l) > 0.05) {
            int is_light = fg_l < bg_l;
            double best = is_light ? bc : wc;
            if (best >= 4.5)
                return is_light;
        }
    }
    return wc >= bc ? 0 : 1;
}

static double sys_gauss(double x)
{
    double d = x - 0.5;
    return exp(-(d * d) / (2.0 * 0.25 * 0.25));
}

static double sys_bell(double l)
{
    double g0 = sys_gauss(0.0);
    return (sys_gauss(l) - g0) / (1.0 - g0);
}

static double sys_sat_curve(const sys_family *f, double l)
{
    double fl = f->sat_max > 0.0 ? f->sat_min / f->sat_max : 1.0;
    return fl + (1.0 - fl) * sys_bell(l);
}

static int sys_level_target(int level, int is_light, double surface_l, double *out)
{
    const sys_curve *cv = &sys_levels[level][is_light ? 1 : 0];
    double x = surface_l;
    if (x < cv->lo || x > cv->hi)
        return 0;
    *out = cv->c[0] + x * (cv->c[1] + x * (cv->c[2] + x * (cv->c[3] + x * (cv->c[4] + x * cv->c[5]))));
    return 1;
}

typedef struct {
    double h, s, l, chroma;
} sys_source;

static sys_source sys_source_of(tui_rgb c)
{
    sys_source src;
    double l_ok, h_ok;
    th_rgb_to_okhsl(c, &src.h, &src.s, &src.l);
    th_rgb_to_oklch(c, &l_ok, &src.chroma, &h_ok);
    return src;
}

static tui_rgb sys_okhsl_rgb(double h, double s, double l)
{
    int r, g, b;
    tui_okhsl_to_rgb(h, s, l, &r, &g, &b);
    return (tui_rgb){(unsigned char)r, (unsigned char)g, (unsigned char)b};
}

static tui_rgb sys_anchored(const sys_source *src, const sys_family *f, double lightness)
{
    double anchor = sys_sat_curve(f, src->l);
    double falloff = anchor > 0.0 ? fmin(1.0, sys_sat_curve(f, lightness) / anchor) : 1.0;
    tui_rgb color = sys_okhsl_rgb(src->h, src->s * falloff, lightness);
    double cap = src->chroma * falloff;
    double l_ok, c_ok, h_ok;
    th_rgb_to_oklch(color, &l_ok, &c_ok, &h_ok);
    if (c_ok <= cap)
        return color;
    int r, g, b;
    oklch_to_rgb(l_ok, cap, src->h, &r, &g, &b);
    return (tui_rgb){(unsigned char)r, (unsigned char)g, (unsigned char)b};
}

static int sys_target(int level, int is_light, double surface_l, double t, double *out)
{
    double extreme = is_light ? 0.0 : 1.0;
    double reached = 0.0;
    int ok = sys_level_target(level, is_light, surface_l, &reached);
    if (!ok && t == 0.0)
        return 0;
    double distance = (ok ? reached : extreme) - surface_l;
    int floor_lvl = is_light ? SYS_LVL_SUBTLE : SYS_LVL_READABLE;
    double fl_val = 0.0;
    int fl_ok = sys_level_target(floor_lvl, is_light, surface_l, &fl_val);
    double fl = (fl_ok ? fl_val : extreme) - surface_l;
    double t1 = t < 1.0 ? t : 1.0;
    double compressed = fabs(distance) > fabs(fl) ? distance - (distance - fl) * t1 : distance;
    double t2 = t > 1.0 ? t - 1.0 : 0.0;
    *out = surface_l + compressed * (1.0 - t2);
    return 1;
}

static tui_rgb sys_paint(tui_token tok, double oklab_l, const sys_source sources[16])
{
    const sys_family *f = &sys_families[sys_token_family[tok]];
    int slot = sys_token_slot(tok);
    return sys_anchored(&sources[slot], f, th_oklab_to_okhsl_l(oklab_l));
}

static tui_rgb sys_limit_panel(tui_token tok, double l, double bg_l, const sys_source sources[16], int is_light)
{
    tui_rgb extreme_text = is_light ? (tui_rgb){0, 0, 0} : (tui_rgb){255, 255, 255};
    tui_rgb color = sys_paint(tok, l, sources);
    if (tui_wcag_contrast(extreme_text, color) >= 4.5)
        return color;
    double lo = bg_l, hi = l;
    for (int i = 0; i < 20; i++) {
        double mid = (lo + hi) * 0.5;
        if (tui_wcag_contrast(extreme_text, sys_paint(tok, mid, sources)) >= 4.5)
            lo = mid;
        else
            hi = mid;
    }
    return sys_paint(tok, lo, sources);
}

static int sys_solve(tui_rgb bg, double bg_l, const sys_source sources[16], int is_light, double t, tui_rgb solved[TUI_T_N])
{
    int lighter = !is_light;
    for (int pass = 0; pass < 2; pass++) {
        for (int tok_i = 0; tok_i < TUI_T_N; tok_i++) {
            tui_token tok = (tui_token)tok_i;
            int is_surface = sys_is_panel(tok) || tok == TUI_T_SCROLLBAR_TRACK;
            if ((pass == 0) != is_surface)
                continue;
            double best_l = 0.0;
            int have = 0;
            for (size_t ri = 0; ri < sizeof sys_rules / sizeof sys_rules[0]; ri++) {
                const sys_rule *r = &sys_rules[ri];
                if (r->token != tok)
                    continue;
                for (int si = 0; si < r->n_on; si++) {
                    tui_rgb surf = r->on[si] == SYS_BG ? bg : solved[r->on[si]];
                    double val = 0.0;
                    if (!sys_target(r->level, is_light, th_oklab_lightness(surf), t, &val) || val < 0.0 || val > 1.0)
                        return 0;
                    if (!have) {
                        best_l = val;
                        have = 1;
                    } else {
                        best_l = lighter ? fmax(best_l, val) : fmin(best_l, val);
                    }
                }
            }
            if (!have)
                return 0;
            solved[tok] = sys_is_panel(tok) ? sys_limit_panel(tok, best_l, bg_l, sources, is_light)
                                            : sys_paint(tok, best_l, sources);
        }
    }
    return 1;
}

static int sys_meets_wcag(tui_rgb c, const tui_rgb *surfaces, int nsurf)
{
    for (int i = 0; i < nsurf; i++)
        if (tui_wcag_contrast(c, surfaces[i]) < 4.5)
            return 0;
    return 1;
}

static tui_rgb sys_with_text_contrast(tui_rgb color, const tui_rgb *surfaces, int nsurf, int lighter)
{
    if (sys_meets_wcag(color, surfaces, nsurf))
        return color;
    double h, s, l;
    th_rgb_to_okhsl(color, &h, &s, &l);
    double extreme = lighter ? 1.0 : 0.0;
    tui_rgb ext = sys_okhsl_rgb(h, s, extreme);
    if (!sys_meets_wcag(ext, surfaces, nsurf))
        return ext;
    double lo = l, hi = extreme;
    for (int i = 0; i < 20; i++) {
        double mid = (lo + hi) * 0.5;
        if (sys_meets_wcag(sys_okhsl_rgb(h, s, mid), surfaces, nsurf))
            hi = mid;
        else
            lo = mid;
    }
    return sys_okhsl_rgb(h, s, hi);
}

int tui_theme_from_palette(const tui_term_palette *pal, tui_theme *out)
{
    static const tui_token fg_tokens[3] = {TUI_T_TEXT, TUI_T_USER_MESSAGE_TEXT, TUI_T_TOOL_TITLE};
    sys_source sources[16];
    tui_rgb solved[TUI_T_N];
    double bg_l, relaxation = 0.0;
    int is_light, lighter;
    if (!pal || !out || !pal->has_bg || (pal->ansi_mask & 0xFFFFu) != 0xFFFFu)
        return -1;
    for (int i = 0; i < 16; i++)
        sources[i] = sys_source_of(pal->ansi[i]);
    is_light = sys_appearance(pal->bg, pal->has_fg, pal->fg);
    lighter = !is_light;
    bg_l = th_oklab_lightness(pal->bg);
    if (!sys_solve(pal->bg, bg_l, sources, is_light, 0.0, solved)) {
        double lo = 0.0, hi = 2.0;
        if (!sys_solve(pal->bg, bg_l, sources, is_light, hi, solved))
            return -1;
        for (int i = 0; i < 20; i++) {
            double mid = (lo + hi) * 0.5;
            tui_rgb attempt[TUI_T_N];
            if (sys_solve(pal->bg, bg_l, sources, is_light, mid, attempt)) {
                hi = mid;
                memcpy(solved, attempt, sizeof solved);
            } else {
                lo = mid;
            }
        }
        relaxation = hi;
    }
    memset(out, 0, sizeof *out);
    (void)snprintf(out->name, sizeof out->name, "system");
    out->appearance = is_light;
    for (int i = 0; i < TUI_T_N; i++) {
        out->c[i].kind = TUI_COLOR_RGB;
        out->c[i].r = solved[i].r;
        out->c[i].g = solved[i].g;
        out->c[i].b = solved[i].b;
    }
    for (size_t fi = 0; fi < sizeof fg_tokens / sizeof fg_tokens[0]; fi++) {
        tui_token tok = fg_tokens[fi];
        tui_rgb surfaces[6];
        int nsurf = 0;
        for (size_t ri = 0; ri < sizeof sys_rules / sizeof sys_rules[0]; ri++) {
            const sys_rule *r = &sys_rules[ri];
            if (r->token != tok)
                continue;
            for (int si = 0; si < r->n_on && nsurf < 6; si++)
                surfaces[nsurf++] = r->on[si] == SYS_BG ? pal->bg : solved[r->on[si]];
        }
        tui_rgb text_col = solved[tok];
        if (pal->has_fg) {
            double needed = 0.0;
            int all_ok = nsurf > 0;
            for (int si = 0; si < nsurf; si++) {
                double val = 0.0;
                if (!sys_target(SYS_LVL_EMPHASIS, is_light, th_oklab_lightness(surfaces[si]), relaxation, &val) ||
                    val < 0.0 || val > 1.0) {
                    all_ok = 0;
                    break;
                }
                needed = si == 0 ? val : (lighter ? fmax(needed, val) : fmin(needed, val));
            }
            if (all_ok) {
                double fg_l = th_oklab_lightness(pal->fg);
                if ((lighter ? fg_l >= needed : fg_l <= needed) && sys_meets_wcag(pal->fg, surfaces, nsurf)) {
                    out->c[tok].kind = TUI_COLOR_DEFAULT;
                    out->c[tok].r = out->c[tok].g = out->c[tok].b = 0;
                    continue;
                }
                sys_source fg_src = sys_source_of(pal->fg);
                text_col = sys_anchored(&fg_src, &sys_families[SYS_FAM_NEUTRAL], th_oklab_to_okhsl_l(needed));
            }
        }
        text_col = sys_with_text_contrast(text_col, surfaces, nsurf, lighter);
        out->c[tok].kind = TUI_COLOR_RGB;
        out->c[tok].r = text_col.r;
        out->c[tok].g = text_col.g;
        out->c[tok].b = text_col.b;
    }
    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);
}