xonecas.io
7814
Ta

tiny-c-agent / files

tiny-c-agent / src / tui / term.h

2.5 KB
1// tiny TUI terminal: display width, sanitising, wrapping, and key decoding.
2//
3// The same text rules mini-coder uses: widths count cells, SGR sequences count
4// zero, and everything else the terminal could act on is dropped before the
5// text is measured, so a row's width is its visible width.
6
7#ifndef TINY_TUI_TERM_H
8#define TINY_TUI_TERM_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13
14#include "util.h"
15
16// Decodes one UTF-8 code point; returns its byte length, or 1 with *cp = the
17// raw byte on malformed input.
18int tiny_utf8_decode(const char *s, size_t len, uint32_t *cp);
19// Encodes a code point and returns its byte length.
20int tiny_utf8_encode(uint32_t cp, char out[4]);
21// Cells one code point occupies.
22int tiny_char_width(uint32_t cp);
23
24int tiny_display_width(const char *text);
25
26// Drops control bytes and every escape sequence but SGR. Returns malloc'd.
27char *tiny_sanitize(const char *text);
28// Expands tabs to `size`-cell stops. Returns malloc'd.
29char *tiny_expand_tabs(const char *text, int size);
30// Splits one logical line into rows no wider than `width`. Returns an owned
31// list of owned rows.
32tiny_strv tiny_wrap_line(const char *text, int width);
33
34typedef enum {
35    TINY_KEY_TEXT,
36    TINY_KEY_SUBMIT,
37    TINY_KEY_NEWLINE,
38    TINY_KEY_BACKSPACE,
39    TINY_KEY_DELETE,
40    TINY_KEY_WORD_BACK,
41    TINY_KEY_LEFT,
42    TINY_KEY_RIGHT,
43    TINY_KEY_WORD_LEFT,
44    TINY_KEY_WORD_RIGHT,
45    TINY_KEY_UP,
46    TINY_KEY_DOWN,
47    TINY_KEY_HOME,
48    TINY_KEY_END,
49    TINY_KEY_DOC_START,
50    TINY_KEY_DOC_END,
51    TINY_KEY_TAB,
52    TINY_KEY_ESCAPE,
53    TINY_KEY_INTERRUPT,
54    TINY_KEY_EOF,
55} tiny_key_type;
56
57typedef struct {
58    tiny_key_type type;
59    char *text;  // TEXT only, malloc'd
60} tiny_key;
61
62typedef void (*tiny_key_fn)(const tiny_key *key, void *user);
63
64typedef struct tiny_key_parser tiny_key_parser;
65
66tiny_key_parser *tiny_key_parser_new(void);
67void tiny_key_parser_free(tiny_key_parser *p);
68
69// Consumes bytes, invoking `emit` for each complete key. Partial sequences are
70// held until more bytes arrive.
71void tiny_key_parser_feed(tiny_key_parser *p, const char *bytes, size_t n,
72                          tiny_key_fn emit, void *user);
73
74// What the buffer may still complete: 0 nothing, 1 a lone ESC, 2 a sequence.
75int tiny_key_parser_pending(tiny_key_parser *p);
76// Emits the held lone ESC (after the 30ms timeout), if any.
77void tiny_key_parser_flush_escape(tiny_key_parser *p, tiny_key_fn emit, void *user);
78// Drops an incomplete sequence (after the 150ms timeout).
79void tiny_key_parser_flush_sequence(tiny_key_parser *p);
80
81#endif