Skip to content

Instantly share code, notes, and snippets.

@JosefLitos
Last active July 21, 2023 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosefLitos/11ae0f78086b4bece35e2a0429ab4a6a to your computer and use it in GitHub Desktop.
Save JosefLitos/11ae0f78086b4bece35e2a0429ab4a6a to your computer and use it in GitHub Desktop.
terminal input tester, including mouse support - find out your key code
// compile: gcc -O2 terminput.c -o terminput
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
system("/bin/stty raw -echo");
int optCnt = argc > 4 ? argc - 1 : 4;
char** opts = malloc(optCnt * sizeof(char*));
opts[0] = ">1u"; // kitty keyboard protocol
// see https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking
opts[1] = "1006";
opts[2] = "1003";
opts[3] = ">4;2m"; // get all modifiers in the same format
for (int i = 1; i < argc; i++) opts[i - 1] = argv[i];
for (int i = 0; i < optCnt; i++)
fprintf(stderr, *opts[i] == '>' ? "\033[%s" : "\033[?%sh", opts[i]);
char seq[20];
int len, leftOver = 0;
while (1) {
int i = 0;
if (!(len = read(0, seq + leftOver, sizeof(seq) - 1 - leftOver) + leftOver)) continue;
leftOver = 0;
seq[len] = 0;
printf("I(");
if (*seq < 0) printf("%s", seq); // not handling utf-8
else do {
if (seq[i] > 31) {
if (seq[i] == 127) printf("\\b");
else printf("%c", seq[i]);
} else printf("^%c", seq[i] + 64);
i++;
} while (i < len && seq[i]);
printf("):");
i = 0;
do {
printf(" %d", seq[i]);
i++;
} while (i < len && seq[i]);
printf("\r\n");
if (*seq == 'q' && len == 1) break;
while (i < len) seq[leftOver++] = seq[i++];
}
for (int i = 0; i < optCnt; i++)
if (*opts[i] != '>') fprintf(stderr, "\033[?%sl", opts[i]);
free(opts);
fprintf(stderr, "\033[>4m\033[<u");
system("/bin/stty sane");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment