Skip to content
pi-c Artifact [8799abc654]
Login

Artifact [8799abc654]

Artifact 8799abc65476b2087f1e37ebc3501069eff5fa9f27cc1f6a53560e668738fdb3:


/* Key decoding and raw mode; see term.h. */
#include "tui/term.h"

#include "tui/width.h"

#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

#define PASTE_END "\x1b[201~"
#define PASTE_END_LEN 6

struct tui_keys {
    char *in; /* bytes not yet consumed: an incomplete sequence */
    size_t in_n, in_cap;
    tui_key *q; /* decoded keys waiting for tui_keys_next */
    size_t q_head, q_n, q_cap;
    int in_paste;
    int stale; /* consecutive flushes that found the same incomplete input */
    char *paste; /* paste content so far */
    size_t paste_n, paste_cap;
};

tui_keys *tui_keys_new(void)
{
    return calloc(1, sizeof(tui_keys));
}

void tui_keys_free(tui_keys *k)
{
    if (!k)
        return;
    for (size_t i = 0; i < k->q_n; i++)
        free(k->q[k->q_head + i].paste);
    free(k->in);
    free(k->q);
    free(k->paste);
    free(k);
}

/* Appends n bytes to a growable byte buffer; 0 or -1. */
static int bytes_add(char **p, size_t *n, size_t *cap, const char *s, size_t add)
{
    if (*n + add + 1 > *cap) {
        size_t c = *cap ? *cap : 64;
        while (c < *n + add + 1)
            c *= 2;
        char *q = realloc(*p, c);
        if (!q)
            return -1;
        *p = q, *cap = c;
    }
    if (add)
        memcpy(*p + *n, s, add);
    *n += add;
    return 0;
}

static tui_key *push(tui_keys *k, tui_key_kind kind)
{
    if (k->q_head + k->q_n == k->q_cap) {
        if (k->q_head > 0) {
            memmove(k->q, k->q + k->q_head, k->q_n * sizeof *k->q);
            k->q_head = 0;
        } else {
            size_t cap = k->q_cap ? k->q_cap * 2 : 16;
            tui_key *q = realloc(k->q, cap * sizeof *q);
            if (!q)
                return NULL;
            k->q = q, k->q_cap = cap;
        }
    }
    tui_key *e = &k->q[k->q_head + k->q_n++];
    memset(e, 0, sizeof *e);
    e->kind = kind;
    return e;
}

static void emit(tui_keys *k, tui_key_kind kind)
{
    (void)push(k, kind);
}

/* Up to three numeric parameters of a CSI, split on ';' (a ':' sub-parameter
 * and anything after it is ignored). Missing ones are 0. */
static void csi_params(const char *p, size_t n, long v[3])
{
    size_t idx = 0;
    int in_sub = 0;
    v[0] = v[1] = v[2] = 0;
    for (size_t i = 0; i < n; i++) {
        if (p[i] == ';') {
            if (++idx == 3)
                return;
            in_sub = 0;
        } else if (p[i] == ':') {
            in_sub = 1;
        } else if (p[i] >= '0' && p[i] <= '9' && !in_sub && v[idx] < 100000) {
            v[idx] = v[idx] * 10 + (p[i] - '0');
        }
    }
}

/* Modifier parameter m (1 + shift 1, alt 2, ctrl 4): is alt or ctrl held? */
static int mod_word(long m)
{
    return m > 1 && ((m - 1) & 6) != 0;
}

static void on_csi(tui_keys *k, const char *p, size_t n, char fin)
{
    long v[3];
    csi_params(p, n, v);
    switch (fin) {
    case 'A': emit(k, v[1] == 3 ? TUI_KEY_ALT_UP : TUI_KEY_UP); break;
    case 'B': emit(k, TUI_KEY_DOWN); break;
    case 'C': emit(k, mod_word(v[1]) ? TUI_KEY_WORD_RIGHT : TUI_KEY_RIGHT); break;
    case 'D': emit(k, mod_word(v[1]) ? TUI_KEY_WORD_LEFT : TUI_KEY_LEFT); break;
    case 'H': emit(k, TUI_KEY_HOME); break;
    case 'F': emit(k, TUI_KEY_END); break;
    case 'Z': emit(k, TUI_KEY_BACKTAB); break;
    case '~':
        switch (v[0]) {
        case 1: case 7: emit(k, TUI_KEY_HOME); break;
        case 4: case 8: emit(k, TUI_KEY_END); break;
        case 3: emit(k, v[1] == 3 ? TUI_KEY_DELETE_WORD_FWD : TUI_KEY_DELETE); break;
        case 5: emit(k, TUI_KEY_PAGEUP); break;
        case 6: emit(k, TUI_KEY_PAGEDOWN); break;
        case 200: k->in_paste = 1, k->paste_n = 0; break;
        case 27: /* xterm modifyOtherKeys: CSI 27 ; mod ; code ~ */
            if (v[2] == 13)
                emit(k, v[1] > 1 ? TUI_KEY_NEWLINE : TUI_KEY_ENTER);
            else if ((v[2] == 112 || v[2] == 80) && v[1] == 6)
                emit(k, TUI_KEY_CTRL_P_BACK);
            break;
        default: break; /* includes a stray 201~ */
        }
        break;
    case 'u': /* kitty: CSI code ; mod u. Only Enter matters here; Shift+Enter is NEWLINE. */
        if (v[0] == 13)
            emit(k, v[1] > 1 ? TUI_KEY_NEWLINE : TUI_KEY_ENTER);
        else if (v[0] == 45 && v[1] == 5)
            emit(k, TUI_KEY_UNDO);
        else if (v[0] == 93 && v[1] == 5)
            emit(k, TUI_KEY_JUMP);
        else if (v[0] == 93 && v[1] == 7)
            emit(k, TUI_KEY_JUMP_BACK);
        else if ((v[0] == 112 || v[0] == 80) && v[1] == 6)
            emit(k, TUI_KEY_CTRL_P_BACK);
        break;
    default: break; /* unknown: dropped */
    }
}

/* Length of a UTF-8 sequence from its lead byte; 0 for a non-lead byte. */
static size_t utf8_need(unsigned char c)
{
    if (c >= 0xC2 && c <= 0xDF) return 2;
    if (c >= 0xE0 && c <= 0xEF) return 3;
    if (c >= 0xF0 && c <= 0xF4) return 4;
    return 0;
}

static void on_ctrl(tui_keys *k, unsigned char c)
{
    switch (c) {
    case 0x01: emit(k, TUI_KEY_HOME); break;
    case 0x02: emit(k, TUI_KEY_LEFT); break;
    case 0x03: emit(k, TUI_KEY_CTRL_C); break;
    case 0x04: emit(k, TUI_KEY_CTRL_D); break;
    case 0x05: emit(k, TUI_KEY_END); break;
    case 0x08: case 0x7f: emit(k, TUI_KEY_BACKSPACE); break;
    case 0x09: emit(k, TUI_KEY_TAB); break;
    case 0x06: emit(k, TUI_KEY_RIGHT); break;
    case 0x07: emit(k, TUI_KEY_CTRL_G); break;
    case 0x0a: emit(k, TUI_KEY_NEWLINE); break;
    case 0x0b: emit(k, TUI_KEY_KILL_LINE); break;
    case 0x0c: emit(k, TUI_KEY_CTRL_L); break;
    case 0x0d: emit(k, TUI_KEY_ENTER); break;
    case 0x0f: emit(k, TUI_KEY_CTRL_O); break;
    case 0x10: emit(k, TUI_KEY_CTRL_P); break;
    case 0x13: emit(k, TUI_KEY_CTRL_S); break;
    case 0x14: emit(k, TUI_KEY_CTRL_T); break;
    case 0x15: emit(k, TUI_KEY_KILL_START); break;
    case 0x17: emit(k, TUI_KEY_DELETE_WORD); break;
    case 0x18: emit(k, TUI_KEY_CTRL_X); break;
    case 0x19: emit(k, TUI_KEY_YANK); break;
    case 0x1a: emit(k, TUI_KEY_CTRL_Z); break;
    case 0x1d: emit(k, TUI_KEY_JUMP); break;
    case 0x1f: emit(k, TUI_KEY_UNDO); break;
    default: break;
    }
}

/* Finishes a bracketed paste: CRLF and CR become LF. */
static void paste_done(tui_keys *k)
{
    /* Always leave paste mode, even when the paste has to be dropped. */
    k->in_paste = 0;
    size_t len = k->paste_n;
    k->paste_n = 0;
    char *out = malloc(len + 1);
    if (!out)
        return;
    size_t o = 0;
    for (size_t i = 0; i < len; i++) {
        if (k->paste[i] == '\r') {
            out[o++] = '\n';
            if (i + 1 < len && k->paste[i + 1] == '\n')
                i++;
        } else {
            out[o++] = k->paste[i];
        }
    }
    out[o] = 0;
    tui_key *e = push(k, TUI_KEY_PASTE);
    if (!e) {
        free(out);
        return;
    }
    e->paste = out;
    e->paste_len = o;
}

/* Decodes what it can from k->in; leaves an incomplete tail at the front. */
static void decode(tui_keys *k)
{
    size_t pos = 0, n = k->in_n;
    const char *in = k->in;
    while (pos < n) {
        if (k->in_paste) {
            const char *end = NULL;
            for (size_t i = pos; i + PASTE_END_LEN <= n; i++) {
                if (memcmp(in + i, PASTE_END, PASTE_END_LEN) == 0) {
                    end = in + i;
                    break;
                }
            }
            if (end) {
                size_t take = (size_t)(end - (in + pos));
                (void)bytes_add(&k->paste, &k->paste_n, &k->paste_cap, in + pos, take);
                pos += take + PASTE_END_LEN;
                paste_done(k);
                continue;
            }
            /* Keep a possible partial terminator (up to 5 bytes) for later. */
            size_t keep = n - pos < PASTE_END_LEN - 1 ? n - pos : PASTE_END_LEN - 1;
            size_t take = n - pos - keep;
            (void)bytes_add(&k->paste, &k->paste_n, &k->paste_cap, in + pos, take);
            pos += take;
            break;
        }
        unsigned char c = (unsigned char)in[pos];
        if (c == 0x1b) {
            if (pos + 1 == n)
                break; /* lone ESC for now */
            unsigned char d = (unsigned char)in[pos + 1];
            if (d == '[') {
                size_t i = pos + 2;
                while (i < n && !((unsigned char)in[i] >= 0x40 && (unsigned char)in[i] <= 0x7E))
                    i++;
                if (i == n)
                    break; /* unfinished CSI */
                on_csi(k, in + pos + 2, i - pos - 2, in[i]);
                pos = i + 1;
            } else if (d == 'O') {
                if (pos + 2 >= n)
                    break;
                switch (in[pos + 2]) {
                case 'A': emit(k, TUI_KEY_UP); break;
                case 'B': emit(k, TUI_KEY_DOWN); break;
                case 'C': emit(k, TUI_KEY_RIGHT); break;
                case 'D': emit(k, TUI_KEY_LEFT); break;
                case 'H': emit(k, TUI_KEY_HOME); break;
                case 'F': emit(k, TUI_KEY_END); break;
                default: break;
                }
                pos += 3;
            } else if (d == 0x1b) {
                emit(k, TUI_KEY_ESC); /* ESC ESC: the first one is a lone Escape */
                pos++;
            } else {
                /* Alt+key. Any other key after ESC is a lone Escape and then
                 * that key: on a slow link, or a busy machine, Escape and what
                 * is typed next arrive in one read, and dropping them as an
                 * unknown Alt+key loses both. */
                switch (d) {
                case 'b': emit(k, TUI_KEY_WORD_LEFT); pos += 2; break;
                case 'f': emit(k, TUI_KEY_WORD_RIGHT); pos += 2; break;
                case 'd': emit(k, TUI_KEY_DELETE_WORD_FWD); pos += 2; break;
                case 'y': emit(k, TUI_KEY_YANK_POP); pos += 2; break;
                case 0x1d: emit(k, TUI_KEY_JUMP_BACK); pos += 2; break;
                case 0x7f: emit(k, TUI_KEY_DELETE_WORD); pos += 2; break;
                case '\r': emit(k, TUI_KEY_NEWLINE); pos += 2; break;
                default: emit(k, TUI_KEY_ESC); pos += 1; break;
                }
            }
        } else if (c < 0x20 || c == 0x7f) {
            on_ctrl(k, c);
            pos++;
        } else if (c < 0x80) {
            tui_key *e = push(k, TUI_KEY_CHAR);
            if (e)
                e->text[0] = (char)c;
            pos++;
        } else {
            size_t need = utf8_need(c);
            if (need == 0) {
                pos++; /* stray continuation or invalid byte */
            } else if (pos + need > n) {
                break; /* incomplete character */
            } else {
                uint32_t cp;
                size_t used = tui_utf8_decode(in + pos, need, &cp);
                if (used == need) {
                    tui_key *e = push(k, TUI_KEY_CHAR);
                    if (e)
                        memcpy(e->text, in + pos, need);
                }
                pos += used;
            }
        }
    }
    memmove(k->in, k->in + pos, n - pos);
    k->in_n = n - pos;
}

void tui_keys_feed(tui_keys *k, const char *buf, size_t n)
{
    k->stale = 0;
    if (bytes_add(&k->in, &k->in_n, &k->in_cap, buf, n) == 0)
        decode(k);
}

int tui_keys_next(tui_keys *k, tui_key *out)
{
    if (k->q_n == 0)
        return 0;
    *out = k->q[k->q_head++];
    k->q_n--;
    return 1;
}

int tui_keys_waiting(const tui_keys *k)
{
    return !k->in_paste && k->in_n > 0;
}

void tui_keys_flush(tui_keys *k)
{
    if (k->in_paste)
        return; /* the paste end is still to come */
    if (k->in_n == 1 && k->in[0] == 0x1b) {
        emit(k, TUI_KEY_ESC);
        k->in_n = 0;
        k->stale = 0;
    } else if (k->in_n > 0 && ++k->stale >= 3) {
        k->in_n = 0; /* an unfinished sequence that never completed */
        k->stale = 0;
    }
}

/* ---- raw mode ---------------------------------------------------------- */

static struct termios saved_termios;
static volatile sig_atomic_t saved_fd = -1;

int tui_term_raw(int fd)
{
    struct termios t;
    if (tcgetattr(fd, &t) != 0)
        return -1;
    if (saved_fd < 0) {
        saved_termios = t;
        saved_fd = fd;
    }
    t.c_iflag &= (tcflag_t) ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON | IXOFF);
    /* Output processing stays on so "\n" still returns the carriage. */
    t.c_lflag &= (tcflag_t) ~(ECHO | ICANON | IEXTEN | ISIG);
    t.c_cflag |= CS8;
    t.c_cc[VMIN] = 1;
    t.c_cc[VTIME] = 0;
    if (tcsetattr(fd, TCSADRAIN, &t) != 0)
        return -1;
    static const char on[] = "\x1b[?2004h";
    if (write(fd, on, sizeof on - 1) < 0)
        return 0; /* raw mode is on; bracketed paste is optional */
    return 0;
}

void tui_term_restore(void)
{
    int fd = saved_fd;
    if (fd < 0)
        return;
    saved_fd = -1;
    static const char off[] = "\x1b[?2004l";
    if (write(fd, off, sizeof off - 1) < 0) {
        /* nothing to do: restoring the mode below matters more */
    }
    (void)tcsetattr(fd, TCSADRAIN, &saved_termios);
}

void tui_term_size(int fd, int *cols, int *rows)
{
    struct winsize ws;
    if (ioctl(fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0 && ws.ws_row > 0) {
        *cols = ws.ws_col;
        *rows = ws.ws_row;
    } else {
        *cols = 80;
        *rows = 24;
    }
}