Make terminal ui binaries work well everywhere

Here's some screenshots of an emulator tui program that was compiled on
Linux, then scp'd it to Windows, Mac, and FreeBSD.

https://justine.storage.googleapis.com/blinkenlights-cmdexe.png
https://justine.storage.googleapis.com/blinkenlights-imac.png
https://justine.storage.googleapis.com/blinkenlights-freebsd.png
https://justine.storage.googleapis.com/blinkenlights-lisp.png

How is this even possible that we have a nontrivial ui binary that just
works on Mac, Windows, Linux, and BSD? Surely a first ever achievement.

Fixed many bugs. Bootstrapped John McCarthy's metacircular evaluator on
bare metal in half the size of Altair BASIC (about 2.5kb) and ran it in
emulator for fun and profit.
This commit is contained in:
Justine Tunney 2020-10-10 21:18:53 -07:00
parent 680daf1210
commit 9e3e985ae5
276 changed files with 7026 additions and 3790 deletions

136
examples/acid2.c Normal file
View file

@ -0,0 +1,136 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/ioctl.h"
#include "libc/calls/struct/termios.h"
#include "libc/fmt/fmt.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/termios.h"
int yn2, xn2;
int yn3, xn3;
char b[128], inbuf[128];
int y, x, yn, xn, my, mx;
struct termios term, oldterm;
int main(int argc, char *argv[]) {
int i;
setvbuf(stdout, inbuf, _IONBF, 128); /* make things slower */
/* raw mode */
ioctl(1, TCGETS, &oldterm);
memcpy(&term, &oldterm, sizeof(term));
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 1;
term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON);
term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL);
term.c_cflag &= ~(CSIZE | PARENB);
term.c_oflag &= ~OPOST;
term.c_cflag |= CS8;
term.c_iflag |= IUTF8;
ioctl(1, TCSETSF, &term);
/* get cursor position and display dimensions */
printf("\e7\e[6n\e[9979;9979H\e[6n\e8");
read(0, b, sizeof(b));
sscanf(b, "\e[%d;%dR\e[%d;%dR", &y, &x, &yn, &xn);
printf("\e[1q"); /* turn on led one */
printf("\e[2J"); /* clear display */
printf("\e#8"); /* fill display with E's */
printf("\e[H");
/* clear display again */
printf("\e[2q"); /* turn on led two */
for (i = 0; i < yn; ++i) {
if (i) printf("\n");
printf(" ");
printf("\e[0K");
}
for (i = 0; i < yn - 1; ++i) {
if (i) printf("\eM");
printf("\e[1K");
}
printf("\e(0"); /* line drawing mode */
printf("\e[3q"); /* turn on led three */
printf("\e[H");
/* move to center */
my = yn / 2;
mx = xn / 2 - 7;
if (y > my) {
printf("\e[%dA", y - my);
} else if (y < my) {
printf("\e[%dB", my - y);
}
if (x > mx) {
printf("\e[%dD", x - mx);
} else if (x < mx) {
printf("\e[%dC", mx - x);
}
printf("\e[90;103m"); /* black on yellow */
printf("\e[90;103ma ` a"); /* draw nose */
printf("\e[0m"); /* reset style */
printf("\e(B"); /* ascii mode */
/* draw corners */
printf("\e[H"); /* top left */
printf("A");
printf("\e[9979C"); /* rightmost */
printf("B");
printf("\e[9979;9979H"); /* bottom right corner */
printf("\e[C"); /* move right gets clamped */
printf("D"); /* write, set redzone flag */
printf("\e[2A"); /* move up, unsets redzone */
/* gnu screen now reports out of bounds position */
/* kitty hasnt got a redzone reporting next line */
printf("\e[6n");
read(0, b, sizeof(b));
sscanf(b, "\e[%d;%dR", &yn2, &xn2);
/* writes to (yn-3,xn-1) normally and (yn-2,0) in gnu screen */
printf("!");
/* draw ruler on top */
printf("\e[H");
for (i = 8; i + 1 < xn; i += 8) {
printf("\e[%dG%d", i + 1, i); /* set column */
}
printf("\e[9979;9979H"); /* bottom right */
printf("\e[9979D"); /* leftmost */
printf("C");
/* let's break gnu screen again with multimonospace redzone */
printf("\e[%d;9979H", yn / 2); /* right middle */
printf("\e[D"); /* left */
printf("");
printf("\e[6n");
read(0, b, sizeof(b));
sscanf(b, "\e[%d;%dR", &yn2, &xn2);
printf("\e[%dH", yn / 2);
printf("%d %d vs. %d %d\r\n", yn, xn, yn2, xn2);
printf("%d %d vs. %d %d\r\n", yn / 2, xn, yn2, xn2);
printf("\e#6double width\e#5\r\n");
printf("\e[3mthis text is so \e[1mitalic\e[0m\r\n");
printf("\e[1;20mpress any fraktur exit\e[0m");
printf("\a");
read(0, b, sizeof(b));
printf("\r\n");
ioctl(1, TCSETS, &oldterm);
return 0;
}

View file

@ -8,12 +8,14 @@
*/
#endif
#include "libc/calls/calls.h"
#include "libc/log/backtrace.h"
#include "libc/log/log.h"
#include "libc/mem/mem.h"
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/fileno.h"
/*
@ -45,9 +47,9 @@
void hello(void) {
gc(malloc(1));
backtrace(stdout);
ShowBacktrace(STDOUT_FILENO, NULL);
setenv("ADDR2LINE", "", true);
backtrace(stdout);
ShowBacktrace(STDOUT_FILENO, NULL);
}
void world(void) {

View file

@ -141,9 +141,9 @@ o/$(MODE)/examples/nesemu1.com.dbg: \
$(APE)
@$(APELINK)
o/$(MODE)/usr/share/dict/words: usr/share/dict/words.gz
usr/share/dict/words: usr/share/dict/words.gz
@$(MKDIR) $(dir $@)
@$(GZ) $(ZFLAGS) <$< >$@
@$(GZ) $(ZFLAGS) -d <$< >$@
o/$(MODE)/examples/ugh.ok: o/$(MODE)/examples/wut.com
$<

View file

@ -15,6 +15,8 @@
#include "libc/sysv/consts/o.h"
#include "third_party/duktape/duktape.h"
STATIC_YOINK("zip_uri_support");
static duk_ret_t NativePrint(duk_context *ctx) {
duk_push_string(ctx, " ");
duk_insert(ctx, 0);

View file

@ -22,6 +22,8 @@
#include "libc/sysv/consts/fileno.h"
#include "libc/x/x.h"
STATIC_YOINK("zip_uri_support");
/**
* @fileoverview Simple Interactive Spell Checker.
*

View file

@ -51,6 +51,7 @@ Contact: antirez@gmail.com\"\n\
*/
#define KILO_VERSION "0.0.1"
#define SYNTAX 1
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
@ -169,14 +170,16 @@ void editorSetStatusMessage(const char *fmt, ...);
* There is no support to highlight patterns currently. */
/* C / C++ */
const char *const C_HL_extensions[] = {".c", ".cpp", NULL};
const char *const C_HL_extensions[] = {".c", ".h", ".cpp", NULL};
const char *const C_HL_keywords[] = {
/* A few C / C++ keywords */
"switch", "if", "while", "for", "break", "continue", "return", "else",
"struct", "union", "typedef", "static", "enum", "class",
/* C types */
"int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|",
"void|", NULL};
"void|", "const|", "size_t|", "ssize_t|", "uint8_t|", "int8_t|",
"uint16_t|", "int16_t|", "uint32_t|", "int32_t|", "uint64_t|", "int64_t|",
NULL};
/* Here we define an array of syntax highlights by extensions, keywords,
* comments delimiters and flags. */
@ -201,7 +204,10 @@ void disableRawMode(int64_t fd) {
/* Called at exit to avoid remaining in raw mode. */
void editorAtExit(void) {
char buf[64];
disableRawMode(STDIN_FILENO);
write(STDOUT_FILENO, buf,
sprintf(buf, "\e[%d;%dH\r\n\r\n\r\n", E.screenrows, E.screencols));
}
/* Raw mode: 1960 magic shit. */
@ -530,8 +536,10 @@ void editorUpdateSyntax(erow *row) {
* state changed. This may recursively affect all the following rows
* in the file. */
int oc = editorRowHasOpenComment(row);
/* if (row->hl_oc != oc && row->idx + 1 < E.numrows) */
/* editorUpdateSyntax(&E.row[row->idx + 1]); */
#if SYNTAX
if (row->hl_oc != oc && row->idx + 1 < E.numrows)
editorUpdateSyntax(&E.row[row->idx + 1]);
#endif
row->hl_oc = oc;
}
@ -586,15 +594,17 @@ void editorUpdateRow(erow *row) {
* respecting tabs, substituting non printable characters with '?'. */
free(row->render);
for (j = 0; j < row->size; j++) {
if (row->chars[j] == CTRL('I')) tabs++;
if (row->chars[j] == '\t') tabs++;
}
row->render = malloc(row->size + tabs * 8 + nonprint * 9 + 1);
idx = 0;
for (j = 0; j < row->size; j++) {
if (row->chars[j] == CTRL('I')) {
if (row->chars[j] == '\t') {
row->render[idx++] = ' ';
while ((idx + 1) % 8 != 0) row->render[idx++] = ' ';
while (idx % 8 != 0) {
row->render[idx++] = ' ';
}
} else {
row->render[idx++] = row->chars[j];
}
@ -603,7 +613,9 @@ void editorUpdateRow(erow *row) {
row->render[idx] = '\0';
/* Update the syntax highlighting attributes of the row. */
/* editorUpdateSyntax(row); */
#if SYNTAX
editorUpdateSyntax(row);
#endif
}
/* Insert a row at the specified position, shifting the other rows on the bottom
@ -918,38 +930,46 @@ void editorRefreshScreen(void) {
r = &E.row[filerow];
int len = r->rsize - E.coloff;
/* int current_color = -1; */
#if SYNTAX
int current_color = -1;
#endif
if (len > 0) {
if (len > E.screencols) len = E.screencols;
char *c = r->render + E.coloff;
/* unsigned char *hl = r->hl + E.coloff; */
#if SYNTAX
unsigned char *hl = r->hl + E.coloff;
#endif
int j;
for (j = 0; j < len; j++) {
/* if (hl[j] == HL_NONPRINT) { */
/* char sym; */
/* abAppend(&ab, "\e[7m", 4); */
/* if (c[j] <= 26) */
/* sym = '@' + c[j]; */
/* else */
/* sym = '?'; */
/* abAppend(&ab, &sym, 1); */
/* abAppend(&ab, "\e[0m", 4); */
/* } else if (hl[j] == HL_NORMAL) { */
/* if (current_color != -1) { */
/* abAppend(&ab, "\e[39m", 5); */
/* current_color = -1; */
/* } */
abAppend(&ab, c + j, 1);
/* } else { */
/* int color = editorSyntaxToColor(hl[j]); */
/* if (color != current_color) { */
/* char buf_[16]; */
/* int clen = snprintf(buf_, sizeof(buf_), "\e[%dm", color); */
/* current_color = color; */
/* abAppend(&ab, buf_, clen); */
/* } */
/* abAppend(&ab, c + j, 1); */
/* } */
#if SYNTAX
if (hl[j] == HL_NONPRINT) {
char sym;
abAppend(&ab, "\e[7m", 4);
if (c[j] <= 26)
sym = '@' + c[j];
else
sym = '?';
abAppend(&ab, &sym, 1);
abAppend(&ab, "\e[0m", 4);
} else if (hl[j] == HL_NORMAL) {
if (current_color != -1) {
abAppend(&ab, "\e[39m", 5);
current_color = -1;
}
#endif
abAppend(&ab, c + j, 1);
#if SYNTAX
} else {
int color = editorSyntaxToColor(hl[j]);
if (color != current_color) {
char buf_[16];
int clen = snprintf(buf_, sizeof(buf_), "\e[%dm", color);
current_color = color;
abAppend(&ab, buf_, clen);
}
abAppend(&ab, c + j, 1);
}
#endif
}
}
abAppend(&ab, "\e[39m", 5);
@ -1200,8 +1220,8 @@ void editorMoveCursor(int key) {
void editorProcessKeypress(int64_t fd) {
/* When the file is modified, requires Ctrl-q to be pressed N times
* before actually quitting. */
int c, times;
static int quit_times;
int c, c2, times, oldcx;
c = editorReadKey(fd);
switch (c) {
@ -1226,16 +1246,16 @@ void editorProcessKeypress(int64_t fd) {
case CTRL('U'):
case CTRL('X'): {
int c2 = editorReadKey(fd);
c2 = editorReadKey(fd);
switch (c2) {
case CTRL('S'):
editorSave();
break;
case CTRL('C'):
/* Erase in Display (ED): Clear from cursor to end of screen. */
write(STDOUT_FILENO, "\r\e[0J", 5);
case CTRL('C'): {
/* write(STDOUT_FILENO, "\r\e[0J", 5); */
exit(0);
break;
}
default: /* ignore */
break;
}
@ -1254,7 +1274,7 @@ void editorProcessKeypress(int64_t fd) {
break;
case CTRL('K'): { /* Kill Line */
int oldcx = E.cx;
oldcx = E.cx;
do {
editorMoveCursor(ARROW_RIGHT);
} while (E.cx);
@ -1294,7 +1314,7 @@ void editorProcessKeypress(int64_t fd) {
case HOME_KEY:
case CTRL('A'):
while (E.cx) editorMoveCursor(ARROW_LEFT);
while (E.cx || E.coloff) editorMoveCursor(ARROW_LEFT);
break;
case END_KEY:
case CTRL('E'):

View file

@ -72,5 +72,9 @@ int main(int argc, char *argv[], char **envp) {
fmt),
kAuxiliaryValues[i].name, key, val, kAuxiliaryValues[i].description);
}
printf("\nSpecial Directories:\n");
printf(" ☼ kTmpPath = %`'s\n", kTmpPath);
printf(" ☼ kNtSystemDirectory = %`'s\n", kNtSystemDirectory);
printf(" ☼ kNtWindowsDirectory = %`'s\n", kNtWindowsDirectory);
return 0;
}

View file

@ -9,16 +9,18 @@
#endif
#include "libc/calls/calls.h"
#include "libc/elf/elf.h"
#include "libc/log/backtrace.h"
#include "libc/log/log.h"
#include "libc/runtime/symbols.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/fileno.h"
int main(int argc, char *argv[]) {
int rc = 0;
char *filename;
struct SymbolTable *tab = NULL;
if ((filename = finddebugbinary()) != NULL &&
(tab = opensymboltable(filename))) {
if ((filename = FindDebugBinary()) != NULL &&
(tab = OpenSymbolTable(filename))) {
for (unsigned i = 0; i < tab->count; ++i) {
printf("%p %s\n", tab->addr_base + tab->symbols[i].addr_rva,
getelfstring(tab->elf, tab->elfsize, tab->name_base,
@ -26,9 +28,9 @@ int main(int argc, char *argv[]) {
}
} else {
perror("printmysymbols");
backtrace(stderr);
ShowBacktrace(STDERR_FILENO, NULL);
rc = 1;
}
closesymboltable(&tab);
CloseSymbolTable(&tab);
return rc;
}

View file

@ -58,6 +58,3 @@ _start: mov $12,%rdx # arg no. 3 is length
jmp 0b
.endfn _start,globl
.source __FILE__
.rodata.cst4
1: .float -1.5

View file

@ -16,7 +16,6 @@
#include "libc/fmt/fmt.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
@ -27,82 +26,138 @@
#include "libc/sysv/consts/termios.h"
#include "libc/x/x.h"
/*
"\e[c" "\e[?1;2c"
"\e[x" "\e[2;1;1;112;112;1;0x"
"\e[>c" "\e[>83;40500;0c"
"\e[6n" "\e[52;1R"
*/
#define CTRL(C) ((C) ^ 0b01000000)
#define ENABLE_MOUSE_TRACKING "\e[?1000;1002;1015;1006h"
#define DISABLE_MOUSE_TRACKING "\e[?1000;1002;1015;1006l"
#define PROBE_DISPLAY_SIZE "\e7\e[9979;9979H\e[6n\e8"
#define CTRL(C) ((C) ^ 0b01000000)
#define PROBE_VT100 "\e[c" /* e.g. "\e[?1;2c", "\e[>0c" */
#define PROBE_SECONDARY "\e[>c" /* "\e[>83;40500;0c" (Screen v4.05.00) */
#define PROBE_PARAMETERS "\e[x" /* e.g. "\e[2;1;1;112;112;1;0x" */
#define PROBE_CURSOR_POSITION "\e[6n" /* e.g. "\e[𝑦;𝑥R" */
#define PROBE_SUN_DTTERM_SIZE "\e[14t" /* e.g. "\e[𝑦;𝑥R" */
char code[512];
struct winsize wsize;
struct termios oldterm;
volatile bool resized, killed;
int fd_;
jmp_buf jb_;
ssize_t got_;
uint8_t buf_[128];
struct TtyIdent ti_;
struct winsize wsize_;
volatile bool resized_;
void OnResize(void) {
resized_ = true;
}
void OnKilled(int sig) {
longjmp(jb_, 128 + sig + 1);
void onresize(void) {
resized = true;
}
void getsome(void) {
if ((got_ = read(fd_, buf_, sizeof(buf_))) == -1 && errno != EINTR) {
printf("%s%s\r\n", "error: ", strerror(errno));
longjmp(jb_, EXIT_FAILURE + 1);
void onkilled(int sig) {
killed = true;
}
void restoretty(void) {
write(1, DISABLE_MOUSE_TRACKING, strlen(DISABLE_MOUSE_TRACKING));
ioctl(1, TCSETS, &oldterm);
}
int rawmode(void) {
static bool once;
struct termios t;
if (!once) {
if (ioctl(1, TCGETS, &oldterm) != -1) {
atexit(restoretty);
} else {
return -1;
}
once = true;
}
if (got_ >= 0) {
printf("%`'.*s\r\n", got_, buf_);
if (got_ > 0 && buf_[0] == CTRL('C')) {
longjmp(jb_, EXIT_SUCCESS + 1);
memcpy(&t, &oldterm, sizeof(t));
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 1;
t.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON |
IGNBRK | BRKINT);
t.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL | ISIG);
t.c_cflag &= ~(CSIZE | PARENB);
t.c_oflag &= ~OPOST;
t.c_cflag |= CS8;
t.c_iflag |= IUTF8;
ioctl(1, TCSETS, &t);
write(1, ENABLE_MOUSE_TRACKING, strlen(ENABLE_MOUSE_TRACKING));
write(1, PROBE_DISPLAY_SIZE, strlen(PROBE_DISPLAY_SIZE));
return 0;
}
void getsize(void) {
if (getttysize(1, &wsize) != -1) {
printf("termios says terminal size is %hu×%hu\r\n", wsize.ws_col,
wsize.ws_row);
} else {
printf("%s\n", strerror(errno));
}
}
const char *describemouseevent(int e) {
static char buf[64];
buf[0] = 0;
if (e & 0x10) {
strcat(buf, " ctrl");
}
if (e & 0x40) {
strcat(buf, " wheel");
if (e & 0x01) {
strcat(buf, " down");
} else {
strcat(buf, " up");
}
} else {
switch (e & 3) {
case 0:
strcat(buf, " left");
break;
case 1:
strcat(buf, " middle");
break;
case 2:
strcat(buf, " right");
break;
default:
unreachable;
}
if (e & 0x20) {
strcat(buf, " drag");
} else if (e & 0x04) {
strcat(buf, " up");
} else {
strcat(buf, " down");
}
}
if (resized_) {
CHECK_NE(-1, getttysize(fd_, &wsize_));
printf("SIGWINCH → %hu×%hu\r\n", wsize_.ws_row, wsize_.ws_col);
resized_ = false;
}
}
void probe(const char *s) {
printf("%`'s → ", s);
write(fd_, s, strlen(s));
getsome();
return buf + 1;
}
int main(int argc, char *argv[]) {
int rc;
char ttyname[64];
struct termios old;
CHECK_NE(-1, (fd_ = open("/dev/tty", O_RDWR)));
CHECK_NE(-1, ttyconfig(fd_, ttysetrawmode, 0, &old));
if (!(rc = setjmp(jb_))) {
xsigaction(SIGTERM, OnKilled, 0, 0, NULL);
xsigaction(SIGWINCH, OnResize, 0, 0, NULL);
if (ttyident(&ti_, STDIN_FILENO, STDOUT_FILENO) != -1) {
ttysendtitle(fd_, "justine was here", &ti_);
fputs(ttydescribe(ttyname, sizeof(ttyname), &ti_), stdout);
int e, c, y, x, n, yn, xn;
xsigaction(SIGTERM, onkilled, 0, 0, NULL);
xsigaction(SIGWINCH, onresize, 0, 0, NULL);
xsigaction(SIGCONT, onresize, 0, 0, NULL);
rawmode();
getsize();
while (!killed) {
if (resized) {
printf("SIGWINCH ");
getsize();
resized = false;
}
if ((n = readansi(0, code, sizeof(code))) == -1) {
if (errno == EINTR) continue;
printf("ERROR: READ: %s\r\n", strerror(errno));
exit(1);
}
printf("%`'.*s ", n, code);
if (iscntrl(code[0]) && !code[1]) {
printf("is CTRL-%c a.k.a. ^%c\r\n", CTRL(code[0]), CTRL(code[0]));
if (code[0] == CTRL('C') || code[0] == CTRL('D')) break;
} else if (startswith(code, "\e[") && endswith(code, "R")) {
yn = 1, xn = 1;
sscanf(code, "\e[%d;%dR", &yn, &xn);
printf("inband signalling says terminal size is %d×%d\r\n", xn, yn);
} else if (startswith(code, "\e[<") &&
(endswith(code, "m") || endswith(code, "M"))) {
e = 0, y = 1, x = 1;
sscanf(code, "\e[<%d;%d;%d%c", &e, &y, &x, &c);
printf("mouse %s at %d×%d\r\n", describemouseevent(e | (c == 'm') << 2),
x, y);
} else {
printf("\r\n");
}
fputs("\r\n", stdout);
probe(PROBE_VT100);
probe(PROBE_SECONDARY);
probe(PROBE_PARAMETERS);
probe(PROBE_CURSOR_POSITION);
/* probe(PROBE_SUN_DTTERM_SIZE); */
getsome();
for (;;) getsome();
}
ttyrestore(fd_, &old);
ttyidentclear(&ti_);
return rc - 1;
return 0;
}