chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

fbttywm.c (25978B)


      1 /* fbttywm - ttywm on the framebuffer. the console with floating windows, no X.
      2  * every screen is a full screen shell, windows float on top in frames drawn with
      3  * the console's own font, and every window is a terminal of ours.
      4  *
      5  *   gcc -static -O2 fbttywm.c -o /fbttywm
      6  *
      7  * super+enter  new window          super+q      close it
      8  * super+tab    next window         super+f      full screen
      9  * super+1..9   tty1 to tty9        super+shift+1..9  send the window there
     10  * super+shift+e  quit
     11  * drag a title, or super+left drag to move. super+right drag to resize. click [x] to close */
     12 #define _XOPEN_SOURCE 700
     13 #include <dirent.h>
     14 #include <errno.h>
     15 #include <fcntl.h>
     16 #include <poll.h>
     17 #include <signal.h>
     18 #include <stdio.h>
     19 #include <stdlib.h>
     20 #include <string.h>
     21 #include <time.h>
     22 #include <unistd.h>
     23 #include <sys/ioctl.h>
     24 #include <sys/mman.h>
     25 #include <sys/wait.h>
     26 #include <termios.h>
     27 #include <linux/fb.h>
     28 #include <linux/input.h>
     29 #include <linux/kd.h>
     30 
     31 #define NSCR    9
     32 #define MAXDEV  32
     33 #define LEN(a)  (sizeof(a) / sizeof(a)[0])
     34 #define MIN(a, b) ((a) < (b) ? (a) : (b))
     35 #define MAX(a, b) ((a) > (b) ? (a) : (b))
     36 
     37 enum { Normal, Esc, Csi, Osc, OscEsc, Charset };
     38 
     39 typedef struct {
     40 	unsigned c;
     41 	unsigned char fg, bg;
     42 } Cell;
     43 
     44 typedef struct {
     45 	int fd, pid, cols, rows;
     46 	Cell *cell, *alt;
     47 	int isalt, x, y, sx, sy, top, bot, wrapnext, hide;
     48 	int fg, bg, bold, rev;
     49 	int st, par[16], np, priv;
     50 	unsigned utf;
     51 	int need;
     52 	char osc[128], title[64];
     53 	int nosc;
     54 } Term;
     55 
     56 typedef struct Win Win;
     57 struct Win {
     58 	Term t;
     59 	int x, y, w, h, scr, full, ox, oy, ow, oh;
     60 	Win *next;
     61 };
     62 
     63 typedef struct {
     64 	int fd, kbd, ax[2], ay[2];
     65 } Dev;
     66 
     67 /* the vga colours, in the order escape codes count them */
     68 static const unsigned pal[16] = {
     69 	0x000000, 0xaa0000, 0x00aa00, 0xaa5500, 0x0000aa, 0xaa00aa, 0x00aaaa, 0xaaaaaa,
     70 	0x555555, 0xff5555, 0x55ff55, 0xffff55, 0x5555ff, 0xff55ff, 0x55ffff, 0xffffff,
     71 };
     72 
     73 /* us keyboard, by evdev key code */
     74 static const char keys[] =
     75 	"\0" "\033" "1234567890-=" "\177" "\t" "qwertyuiop[]" "\r" "\0" "asdfghjkl;'`" "\0" "\\" "zxcvbnm,./" "\0" "*" "\0" " ";
     76 static const char shiftkeys[] =
     77 	"\0" "\033" "!@#$%^&*()_+" "\177" "\t" "QWERTYUIOP{}" "\r" "\0" "ASDFGHJKL:\"~" "\0" "|" "ZXCVBNM<>?" "\0" "*" "\0" " ";
     78 
     79 static unsigned char font[512 * 32 * 4];
     80 static unsigned short uni[65536];
     81 static int fw, fh, fpitch;
     82 
     83 static unsigned char *fb;
     84 static int fbw, fbh, fbline, fbbpp;
     85 static struct fb_var_screeninfo var;
     86 
     87 static int cols, rows, cur, tty = -1, running = 1, dirty = 1;
     88 static Cell *scr, *old;
     89 static Term shell[NSCR];
     90 static Win *wins, *sel;
     91 static Dev dev[MAXDEV];
     92 static int ndev;
     93 static int mx, my, shift, ctrl, alt, super, caps;
     94 static Win *drag;
     95 static int dragrs, dragx, dragy;
     96 static char *sh;
     97 
     98 static void
     99 die(const char *s)
    100 {
    101 	if (tty >= 0)
    102 		ioctl(tty, KDSETMODE, KD_TEXT);
    103 	fprintf(stderr, "fbttywm: %s: %s\n", s, strerror(errno));
    104 	exit(1);
    105 }
    106 
    107 /* ---- the font: the one the console uses, from the kernel ---- */
    108 static void
    109 getfont(void)
    110 {
    111 	struct console_font_op op = { KD_FONT_OP_GET, 0, 32, 32, 512, font };
    112 	struct unipair *u;
    113 	struct unimapdesc d;
    114 	int i;
    115 
    116 	if (ioctl(tty, KDFONTOP, &op) < 0)
    117 		die("can't read the console's font");
    118 	fw = op.width, fh = op.height, fpitch = (fw + 7) / 8;
    119 	memset(uni, 0xff, sizeof uni);
    120 	u = calloc(16384, sizeof *u);
    121 	d.entry_ct = 16384, d.entries = u;
    122 	if (ioctl(tty, GIO_UNIMAP, &d) == 0) {
    123 		for (i = 0; i < d.entry_ct; i++)
    124 			if (uni[u[i].unicode] == 0xffff)
    125 				uni[u[i].unicode] = u[i].fontpos;
    126 	} else {
    127 		for (i = 32; i < 127; i++)
    128 			uni[i] = i;
    129 	}
    130 	free(u);
    131 }
    132 
    133 static int
    134 glyph(unsigned c)
    135 {
    136 	if (c < 65536 && uni[c] != 0xffff)
    137 		return uni[c];
    138 	return uni['?'] != 0xffff ? uni['?'] : '?';
    139 }
    140 
    141 /* ---- the screen ---- */
    142 static unsigned
    143 pixel(int i)
    144 {
    145 	unsigned c = pal[i], r = c >> 16, g = c >> 8 & 255, b = c & 255;
    146 
    147 	r >>= 8 - var.red.length, g >>= 8 - var.green.length, b >>= 8 - var.blue.length;
    148 	return r << var.red.offset | g << var.green.offset | b << var.blue.offset;
    149 }
    150 
    151 static void
    152 drawcell(int x, int y, Cell *c)
    153 {
    154 	unsigned char *g = font + glyph(c->c) * 32 * fpitch;
    155 	unsigned f = pixel(c->fg), b = pixel(c->bg);
    156 	int i, j;
    157 
    158 	for (i = 0; i < fh; i++) {
    159 		unsigned char *p = fb + (y * fh + i) * fbline + x * fw * (fbbpp / 8);
    160 		for (j = 0; j < fw; j++) {
    161 			unsigned v = g[i * fpitch + j / 8] & 0x80 >> (j % 8) ? f : b;
    162 			if (fbbpp == 32)
    163 				((unsigned *)p)[j] = v;
    164 			else
    165 				((unsigned short *)p)[j] = v;
    166 		}
    167 	}
    168 }
    169 
    170 static void
    171 openfb(void)
    172 {
    173 	struct fb_fix_screeninfo fix;
    174 	int fd = open("/dev/fb0", O_RDWR);
    175 
    176 	if (fd < 0)
    177 		die("/dev/fb0");
    178 	if (ioctl(fd, FBIOGET_VSCREENINFO, &var) < 0 || ioctl(fd, FBIOGET_FSCREENINFO, &fix) < 0)
    179 		die("/dev/fb0");
    180 	fbw = var.xres, fbh = var.yres, fbline = fix.line_length, fbbpp = var.bits_per_pixel;
    181 	if (fbbpp != 32 && fbbpp != 16) {
    182 		errno = EINVAL;
    183 		die("only 16 and 32 bit framebuffers");
    184 	}
    185 	fb = mmap(NULL, fbline * fbh, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    186 	if (fb == MAP_FAILED)
    187 		die("mmap /dev/fb0");
    188 	cols = fbw / fw, rows = fbh / fh;
    189 	scr = calloc(cols * rows, sizeof *scr);
    190 	old = calloc(cols * rows, sizeof *old);
    191 	memset(old, 0xff, cols * rows * sizeof *old);
    192 	memset(fb, 0, fbline * fbh);
    193 }
    194 
    195 /* ---- terminals ---- */
    196 static void
    197 clearcells(Term *t, int from, int to)
    198 {
    199 	for (; from < to; from++)
    200 		t->cell[from] = (Cell){ ' ', 7, t->bg };
    201 }
    202 
    203 static void
    204 tsize(Term *t)
    205 {
    206 	struct winsize ws = { t->rows, t->cols, t->cols * fw, t->rows * fh };
    207 
    208 	ioctl(t->fd, TIOCSWINSZ, &ws);
    209 }
    210 
    211 static void
    212 tnew(Term *t, int c, int r)
    213 {
    214 	char *pts;
    215 	int fd;
    216 
    217 	memset(t, 0, sizeof *t);
    218 	t->cols = c, t->rows = r, t->bot = r - 1, t->fg = 7;
    219 	t->cell = calloc(c * r, sizeof(Cell));
    220 	t->alt = calloc(c * r, sizeof(Cell));
    221 	clearcells(t, 0, c * r);
    222 	snprintf(t->title, sizeof t->title, "%s", strrchr(sh, '/') ? strrchr(sh, '/') + 1 : sh);
    223 	if ((t->fd = posix_openpt(O_RDWR | O_NOCTTY)) < 0 || grantpt(t->fd) < 0 || unlockpt(t->fd) < 0)
    224 		die("a new terminal");
    225 	pts = ptsname(t->fd);
    226 	tsize(t);
    227 	if ((t->pid = fork()) == 0) {
    228 		setsid();
    229 		if ((fd = open(pts, O_RDWR)) < 0)
    230 			_exit(1);
    231 		ioctl(fd, TIOCSCTTY, 0);
    232 		dup2(fd, 0), dup2(fd, 1), dup2(fd, 2);
    233 		if (fd > 2)
    234 			close(fd);
    235 		setenv("TERM", "linux", 1);
    236 		execl(sh, sh, (char *)NULL);
    237 		_exit(127);
    238 	}
    239 	fcntl(t->fd, F_SETFL, O_NONBLOCK);
    240 }
    241 
    242 static void
    243 tfree(Term *t)
    244 {
    245 	if (t->pid > 0)
    246 		kill(t->pid, SIGHUP);
    247 	if (t->fd > 0)
    248 		close(t->fd);
    249 	free(t->cell), free(t->alt);
    250 	t->pid = 0, t->fd = 0, t->cell = t->alt = NULL;
    251 }
    252 
    253 static void
    254 tresize(Term *t, int c, int r)
    255 {
    256 	Cell *n[2];
    257 	Cell *o[2] = { t->cell, t->alt };
    258 	int i, y, x;
    259 
    260 	if (c == t->cols && r == t->rows)
    261 		return;
    262 	for (i = 0; i < 2; i++) {
    263 		n[i] = calloc(c * r, sizeof(Cell));
    264 		for (y = 0; y < r; y++)
    265 			for (x = 0; x < c; x++)
    266 				n[i][y * c + x] = y < t->rows && x < t->cols ? o[i][y * t->cols + x] : (Cell){ ' ', 7, 0 };
    267 		free(o[i]);
    268 	}
    269 	t->cell = n[0], t->alt = n[1];
    270 	t->cols = c, t->rows = r, t->top = 0, t->bot = r - 1;
    271 	t->x = MIN(t->x, c - 1), t->y = MIN(t->y, r - 1);
    272 	t->wrapnext = 0;
    273 	tsize(t);
    274 }
    275 
    276 static void
    277 scrollup(Term *t, int top, int bot, int n)
    278 {
    279 	n = MIN(n, bot - top + 1);
    280 	memmove(t->cell + top * t->cols, t->cell + (top + n) * t->cols, (bot - top + 1 - n) * t->cols * sizeof(Cell));
    281 	clearcells(t, (bot - n + 1) * t->cols, (bot + 1) * t->cols);
    282 }
    283 
    284 static void
    285 scrolldown(Term *t, int top, int bot, int n)
    286 {
    287 	n = MIN(n, bot - top + 1);
    288 	memmove(t->cell + (top + n) * t->cols, t->cell + top * t->cols, (bot - top + 1 - n) * t->cols * sizeof(Cell));
    289 	clearcells(t, top * t->cols, (top + n) * t->cols);
    290 }
    291 
    292 static void
    293 newline(Term *t)
    294 {
    295 	if (t->y == t->bot)
    296 		scrollup(t, t->top, t->bot, 1);
    297 	else if (t->y < t->rows - 1)
    298 		t->y++;
    299 }
    300 
    301 static void
    302 moveto(Term *t, int x, int y)
    303 {
    304 	t->x = MAX(0, MIN(x, t->cols - 1));
    305 	t->y = MAX(0, MIN(y, t->rows - 1));
    306 	t->wrapnext = 0;
    307 }
    308 
    309 static void
    310 reply(Term *t, const char *s)
    311 {
    312 	write(t->fd, s, strlen(s));
    313 }
    314 
    315 static void
    316 tputc(Term *t, unsigned c)
    317 {
    318 	Cell *p;
    319 	int f = t->fg + (t->bold && t->fg < 8 ? 8 : 0);
    320 
    321 	if (t->wrapnext) {
    322 		t->x = 0, t->wrapnext = 0;
    323 		newline(t);
    324 	}
    325 	p = &t->cell[t->y * t->cols + t->x];
    326 	p->c = c;
    327 	p->fg = t->rev ? t->bg : f;
    328 	p->bg = t->rev ? f : t->bg;
    329 	if (t->x == t->cols - 1)
    330 		t->wrapnext = 1;
    331 	else
    332 		t->x++;
    333 }
    334 
    335 static void
    336 altscreen(Term *t, int on)
    337 {
    338 	Cell *c;
    339 
    340 	if (on == t->isalt)
    341 		return;
    342 	c = t->cell, t->cell = t->alt, t->alt = c;
    343 	t->isalt = on;
    344 	if (on)
    345 		clearcells(t, 0, t->cols * t->rows);
    346 }
    347 
    348 static void
    349 sgr(Term *t)
    350 {
    351 	int i, p;
    352 
    353 	for (i = 0; i < t->np; i++) {
    354 		p = t->par[i];
    355 		if (p == 0)
    356 			t->fg = 7, t->bg = 0, t->bold = t->rev = 0;
    357 		else if (p == 1)
    358 			t->bold = 1;
    359 		else if (p == 22)
    360 			t->bold = 0;
    361 		else if (p == 7)
    362 			t->rev = 1;
    363 		else if (p == 27)
    364 			t->rev = 0;
    365 		else if (p >= 30 && p <= 37)
    366 			t->fg = p - 30;
    367 		else if (p == 39)
    368 			t->fg = 7;
    369 		else if (p >= 40 && p <= 47)
    370 			t->bg = p - 40;
    371 		else if (p == 49)
    372 			t->bg = 0;
    373 		else if (p >= 90 && p <= 97)
    374 			t->fg = p - 90 + 8;
    375 		else if (p >= 100 && p <= 107)
    376 			t->bg = p - 100 + 8;
    377 		else if ((p == 38 || p == 48) && i + 2 < t->np && t->par[i + 1] == 5) {
    378 			if (t->par[i + 2] < 16)
    379 				*(p == 38 ? &t->fg : &t->bg) = t->par[i + 2];
    380 			i += 2;
    381 		} else if ((p == 38 || p == 48) && t->par[i + 1] == 2)
    382 			i += 4;
    383 	}
    384 }
    385 
    386 static void
    387 csi(Term *t, int f)
    388 {
    389 	int n = t->par[0] ? t->par[0] : 1, i, at = t->y * t->cols + t->x;
    390 	char s[32];
    391 
    392 	switch (f) {
    393 	case '@':
    394 		n = MIN(n, t->cols - t->x);
    395 		memmove(t->cell + at + n, t->cell + at, (t->cols - t->x - n) * sizeof(Cell));
    396 		clearcells(t, at, at + n);
    397 		break;
    398 	case 'A': moveto(t, t->x, t->y - n); break;
    399 	case 'B': case 'e': moveto(t, t->x, t->y + n); break;
    400 	case 'C': case 'a': moveto(t, t->x + n, t->y); break;
    401 	case 'D': moveto(t, t->x - n, t->y); break;
    402 	case 'E': moveto(t, 0, t->y + n); break;
    403 	case 'F': moveto(t, 0, t->y - n); break;
    404 	case 'G': case '`': moveto(t, n - 1, t->y); break;
    405 	case 'd': moveto(t, t->x, n - 1); break;
    406 	case 'H': case 'f':
    407 		moveto(t, (t->np > 1 && t->par[1] ? t->par[1] : 1) - 1, n - 1);
    408 		break;
    409 	case 'J':
    410 		if (t->par[0] == 0)
    411 			clearcells(t, at, t->cols * t->rows);
    412 		else if (t->par[0] == 1)
    413 			clearcells(t, 0, at + 1);
    414 		else
    415 			clearcells(t, 0, t->cols * t->rows);
    416 		break;
    417 	case 'K':
    418 		if (t->par[0] == 0)
    419 			clearcells(t, at, (t->y + 1) * t->cols);
    420 		else if (t->par[0] == 1)
    421 			clearcells(t, t->y * t->cols, at + 1);
    422 		else
    423 			clearcells(t, t->y * t->cols, (t->y + 1) * t->cols);
    424 		break;
    425 	case 'L':
    426 		if (t->y >= t->top && t->y <= t->bot)
    427 			scrolldown(t, t->y, t->bot, n);
    428 		break;
    429 	case 'M':
    430 		if (t->y >= t->top && t->y <= t->bot)
    431 			scrollup(t, t->y, t->bot, n);
    432 		break;
    433 	case 'P':
    434 		n = MIN(n, t->cols - t->x);
    435 		memmove(t->cell + at, t->cell + at + n, (t->cols - t->x - n) * sizeof(Cell));
    436 		clearcells(t, (t->y + 1) * t->cols - n, (t->y + 1) * t->cols);
    437 		break;
    438 	case 'X':
    439 		clearcells(t, at, at + MIN(n, t->cols - t->x));
    440 		break;
    441 	case 'm':
    442 		sgr(t);
    443 		break;
    444 	case 'r':
    445 		t->top = (t->par[0] ? t->par[0] : 1) - 1;
    446 		t->bot = (t->np > 1 && t->par[1] ? t->par[1] : t->rows) - 1;
    447 		if (t->top >= t->bot || t->bot >= t->rows)
    448 			t->top = 0, t->bot = t->rows - 1;
    449 		moveto(t, 0, 0);
    450 		break;
    451 	case 's': t->sx = t->x, t->sy = t->y; break;
    452 	case 'u': moveto(t, t->sx, t->sy); break;
    453 	case 'h': case 'l':
    454 		for (i = 0; t->priv && i < t->np; i++) {
    455 			if (t->par[i] == 25)
    456 				t->hide = f == 'l';
    457 			else if (t->par[i] == 1049 || t->par[i] == 47 || t->par[i] == 1047) {
    458 				if (f == 'h' && t->par[i] == 1049)
    459 					t->sx = t->x, t->sy = t->y;
    460 				altscreen(t, f == 'h');
    461 				if (f == 'l' && t->par[i] == 1049)
    462 					moveto(t, t->sx, t->sy);
    463 			}
    464 		}
    465 		break;
    466 	case 'n':
    467 		if (t->par[0] == 6) {
    468 			snprintf(s, sizeof s, "\033[%d;%dR", t->y + 1, t->x + 1);
    469 			reply(t, s);
    470 		}
    471 		break;
    472 	case 'c':
    473 		reply(t, "\033[?6c");
    474 		break;
    475 	}
    476 }
    477 
    478 static void
    479 esc(Term *t, int c)
    480 {
    481 	t->st = Normal;
    482 	switch (c) {
    483 	case '[':
    484 		t->st = Csi, t->np = 0, t->priv = 0;
    485 		memset(t->par, 0, sizeof t->par);
    486 		break;
    487 	case ']': t->st = Osc, t->nosc = 0; break;
    488 	case '(': case ')': t->st = Charset; break;
    489 	case '7': t->sx = t->x, t->sy = t->y; break;
    490 	case '8': moveto(t, t->sx, t->sy); break;
    491 	case 'D': newline(t); break;
    492 	case 'E': t->x = 0, newline(t); break;
    493 	case 'M':
    494 		if (t->y == t->top)
    495 			scrolldown(t, t->top, t->bot, 1);
    496 		else if (t->y > 0)
    497 			t->y--;
    498 		break;
    499 	case 'c':
    500 		t->fg = 7, t->bg = 0, t->bold = t->rev = t->hide = 0;
    501 		t->top = 0, t->bot = t->rows - 1;
    502 		altscreen(t, 0);
    503 		clearcells(t, 0, t->cols * t->rows);
    504 		moveto(t, 0, 0);
    505 		break;
    506 	}
    507 }
    508 
    509 /* a title from \033]0;title\007 or \033]2;title\007 */
    510 static void
    511 oscdone(Term *t)
    512 {
    513 	t->osc[t->nosc] = 0;
    514 	if ((t->osc[0] == '0' || t->osc[0] == '2') && t->osc[1] == ';')
    515 		snprintf(t->title, sizeof t->title, "%s", t->osc + 2);
    516 	t->st = Normal;
    517 }
    518 
    519 static void
    520 tfeed(Term *t, unsigned char *s, int n)
    521 {
    522 	int b;
    523 
    524 	for (; n-- > 0; s++) {
    525 		b = *s;
    526 		if (t->st == Osc) {
    527 			if (b == 7)
    528 				oscdone(t);
    529 			else if (b == 033)
    530 				t->st = OscEsc;
    531 			else if (t->nosc < (int)sizeof t->osc - 1)
    532 				t->osc[t->nosc++] = b;
    533 			continue;
    534 		}
    535 		if (t->st == OscEsc) {
    536 			oscdone(t);
    537 			continue;
    538 		}
    539 		if (t->st == Charset) {
    540 			t->st = Normal;
    541 			continue;
    542 		}
    543 		if (b < 32 || b == 127) {
    544 			switch (b) {
    545 			case '\b': moveto(t, t->x - 1, t->y); break;
    546 			case '\t': moveto(t, (t->x / 8 + 1) * 8, t->y); break;
    547 			case '\n': case '\v': case '\f': t->wrapnext = 0, newline(t); break;
    548 			case '\r': t->x = 0, t->wrapnext = 0; break;
    549 			case 033: t->st = Esc; break;
    550 			case 030: case 032: t->st = Normal; break;
    551 			}
    552 			continue;
    553 		}
    554 		if (t->st == Esc) {
    555 			esc(t, b);
    556 			continue;
    557 		}
    558 		if (t->st == Csi) {
    559 			if (b == '?' || b == '>')
    560 				t->priv = 1;
    561 			else if (b >= '0' && b <= '9')
    562 				t->par[t->np] = MIN(t->par[t->np] * 10 + b - '0', 9999);
    563 			else if (b == ';') {
    564 				if (t->np < (int)LEN(t->par) - 1)
    565 					t->np++;
    566 			} else if (b >= 0x40 && b <= 0x7e) {
    567 				t->np++;
    568 				t->st = Normal;
    569 				csi(t, b);
    570 			}
    571 			continue;
    572 		}
    573 		/* utf-8 */
    574 		if (b < 0x80)
    575 			tputc(t, b), t->need = 0;
    576 		else if ((b & 0xc0) == 0x80 && t->need) {
    577 			t->utf = t->utf << 6 | (b & 0x3f);
    578 			if (--t->need == 0)
    579 				tputc(t, t->utf);
    580 		} else if ((b & 0xe0) == 0xc0)
    581 			t->utf = b & 0x1f, t->need = 1;
    582 		else if ((b & 0xf0) == 0xe0)
    583 			t->utf = b & 0x0f, t->need = 2;
    584 		else if ((b & 0xf8) == 0xf0)
    585 			t->utf = b & 0x07, t->need = 3;
    586 		else
    587 			tputc(t, '?'), t->need = 0;
    588 	}
    589 }
    590 
    591 /* ---- windows ---- */
    592 static void
    593 inner(Win *w, int *x, int *y, int *c, int *r)
    594 {
    595 	int f = !w->full;
    596 
    597 	*x = w->x + f, *y = w->y + f, *c = w->w - 2 * f, *r = w->h - 2 * f;
    598 }
    599 
    600 static Term *
    601 focused(void)
    602 {
    603 	return sel ? &sel->t : &shell[cur];
    604 }
    605 
    606 static void
    607 raise_(Win *w)
    608 {
    609 	Win **p;
    610 
    611 	for (p = &wins; *p; p = &(*p)->next)
    612 		if (*p == w) {
    613 			*p = w->next;
    614 			break;
    615 		}
    616 	for (p = &wins; *p; p = &(*p)->next)
    617 		;
    618 	*p = w, w->next = NULL;
    619 	sel = w;
    620 }
    621 
    622 static Win *
    623 topwin(void)
    624 {
    625 	Win *w, *top = NULL;
    626 
    627 	for (w = wins; w; w = w->next)
    628 		if (w->scr == cur)
    629 			top = w;
    630 	return top;
    631 }
    632 
    633 static void
    634 newwin(void)
    635 {
    636 	static int n;
    637 	Win *w = calloc(1, sizeof *w);
    638 
    639 	w->w = MAX(cols / 2, 20), w->h = MAX((rows - 1) / 2, 6);
    640 	w->x = (cols - w->w) / 2 + n % 5 * 2 - 4, w->y = (rows - 1 - w->h) / 2 + n % 5 - 2;
    641 	w->x = MAX(0, w->x), w->y = MAX(0, w->y);
    642 	w->scr = cur;
    643 	n++;
    644 	tnew(&w->t, w->w - 2, w->h - 2);
    645 	raise_(w);
    646 }
    647 
    648 static void
    649 closewin(Win *w)
    650 {
    651 	Win **p;
    652 
    653 	for (p = &wins; *p; p = &(*p)->next)
    654 		if (*p == w) {
    655 			*p = w->next;
    656 			break;
    657 		}
    658 	if (drag == w)
    659 		drag = NULL;
    660 	tfree(&w->t);
    661 	free(w);
    662 	sel = topwin();
    663 }
    664 
    665 static void
    666 fit(Win *w)
    667 {
    668 	int x, y, c, r;
    669 
    670 	inner(w, &x, &y, &c, &r);
    671 	tresize(&w->t, c, r);
    672 }
    673 
    674 static void
    675 fullscreen(Win *w)
    676 {
    677 	if ((w->full = !w->full)) {
    678 		w->ox = w->x, w->oy = w->y, w->ow = w->w, w->oh = w->h;
    679 		w->x = 0, w->y = 0, w->w = cols, w->h = rows - 1;
    680 	} else
    681 		w->x = w->ox, w->y = w->oy, w->w = w->ow, w->h = w->oh;
    682 	fit(w);
    683 }
    684 
    685 static void
    686 view(int i)
    687 {
    688 	cur = i;
    689 	if (!shell[i].pid)
    690 		tnew(&shell[i], cols, rows - 1);
    691 	sel = topwin();
    692 }
    693 
    694 static void
    695 sendwin(int i)
    696 {
    697 	if (!sel)
    698 		return;
    699 	sel->scr = i;
    700 	sel = topwin();
    701 }
    702 
    703 static void
    704 nextwin(void)
    705 {
    706 	Win *w;
    707 
    708 	for (w = wins; w; w = w->next)
    709 		if (w->scr == cur && w != sel) {
    710 			raise_(w);
    711 			return;
    712 		}
    713 }
    714 
    715 /* ---- what goes on the screen ---- */
    716 static void
    717 put(int x, int y, unsigned c, int fg, int bg)
    718 {
    719 	if (x < 0 || y < 0 || x >= cols || y >= rows - 1)
    720 		return;
    721 	scr[y * cols + x] = (Cell){ c, fg, bg };
    722 }
    723 
    724 static void
    725 puts_(int x, int y, const char *s, int fg, int bg)
    726 {
    727 	for (; *s; s++, x++)
    728 		put(x, y, (unsigned char)*s, fg, bg);
    729 }
    730 
    731 /* ┌─[ name ]───[x]┐ */
    732 static void
    733 frame(Win *w)
    734 {
    735 	int fg = w == sel ? 15 : 7, i, x, n;
    736 	char name[80];
    737 
    738 	put(w->x, w->y, 0x250c, fg, 0);
    739 	put(w->x + 1, w->y, 0x2500, fg, 0);
    740 	snprintf(name, sizeof name, "[ %s ]", w->t.title);
    741 	n = MIN((int)strlen(name), w->w - 7);
    742 	name[MAX(n, 0)] = 0;
    743 	puts_(w->x + 2, w->y, name, fg, 0);
    744 	for (x = w->x + 2 + n; x < w->x + w->w - 4; x++)
    745 		put(x, w->y, 0x2500, fg, 0);
    746 	puts_(w->x + w->w - 4, w->y, "[x]", fg, 0);
    747 	put(w->x + w->w - 1, w->y, 0x2510, fg, 0);
    748 	for (i = 1; i < w->h - 1; i++) {
    749 		put(w->x, w->y + i, 0x2502, fg, 0);
    750 		put(w->x + w->w - 1, w->y + i, 0x2502, fg, 0);
    751 	}
    752 	put(w->x, w->y + w->h - 1, 0x2514, fg, 0);
    753 	for (x = w->x + 1; x < w->x + w->w - 1; x++)
    754 		put(x, w->y + w->h - 1, 0x2500, fg, 0);
    755 	put(w->x + w->w - 1, w->y + w->h - 1, 0x2518, fg, 0);
    756 }
    757 
    758 static void
    759 bar(void)
    760 {
    761 	char s[128], bat[32] = "";
    762 	time_t now = time(NULL);
    763 	struct tm *tm = localtime(&now);
    764 	FILE *f;
    765 	int i, n, y = rows - 1;
    766 
    767 	if ((f = fopen("/sys/class/power_supply/BAT0/capacity", "r"))) {
    768 		if (fscanf(f, "%d", &n) == 1)
    769 			snprintf(bat, sizeof bat, "bat %d%%  ", n);
    770 		fclose(f);
    771 	}
    772 	n = strftime(s, sizeof s, "%a %d %b  %H:%M", tm);
    773 	snprintf(s + n, sizeof s - n, "  tty%d ", cur + 1);
    774 	for (i = 0; i < cols; i++)
    775 		scr[y * cols + i] = (Cell){ ' ', 7, 0 };
    776 	n = strlen(bat) + strlen(s);
    777 	for (i = 0; bat[i]; i++)
    778 		scr[y * cols + cols - n + i] = (Cell){ (unsigned char)bat[i], 7, 0 };
    779 	for (i = 0; s[i]; i++)
    780 		scr[y * cols + cols - strlen(s) + i] = (Cell){ (unsigned char)s[i], 7, 0 };
    781 }
    782 
    783 static void
    784 invert(int x, int y)
    785 {
    786 	Cell *c;
    787 	unsigned char t;
    788 
    789 	if (x < 0 || y < 0 || x >= cols || y >= rows)
    790 		return;
    791 	c = &scr[y * cols + x];
    792 	t = c->fg, c->fg = c->bg, c->bg = t;
    793 	if (c->fg == c->bg)
    794 		c->fg = c->bg ? 0 : 7;
    795 }
    796 
    797 static void
    798 compose(void)
    799 {
    800 	Term *t = &shell[cur];
    801 	Win *w;
    802 	int x, y, ix, iy, c, r;
    803 
    804 	for (y = 0; y < rows - 1; y++)
    805 		for (x = 0; x < cols; x++)
    806 			scr[y * cols + x] = t->cell[y * t->cols + x];
    807 	for (w = wins; w; w = w->next) {
    808 		if (w->scr != cur)
    809 			continue;
    810 		if (!w->full)
    811 			frame(w);
    812 		inner(w, &ix, &iy, &c, &r);
    813 		for (y = 0; y < MIN(r, w->t.rows); y++)
    814 			for (x = 0; x < MIN(c, w->t.cols); x++) {
    815 				Cell *p = &w->t.cell[y * w->t.cols + x];
    816 				put(ix + x, iy + y, p->c, p->fg, p->bg);
    817 			}
    818 	}
    819 	bar();
    820 	t = focused();
    821 	if (!t->hide) {
    822 		ix = iy = 0;
    823 		if (sel)
    824 			inner(sel, &ix, &iy, &c, &r);
    825 		if (iy + t->y < rows - 1)
    826 			invert(ix + t->x, iy + t->y);
    827 	}
    828 	invert(mx / fw, my / fh);
    829 }
    830 
    831 static void
    832 draw(void)
    833 {
    834 	int i;
    835 
    836 	compose();
    837 	for (i = 0; i < cols * rows; i++)
    838 		if (memcmp(&scr[i], &old[i], sizeof(Cell))) {
    839 			drawcell(i % cols, i / cols, &scr[i]);
    840 			old[i] = scr[i];
    841 		}
    842 	dirty = 0;
    843 }
    844 
    845 /* ---- keyboard and mouse ---- */
    846 static void
    847 opendevs(void)
    848 {
    849 	unsigned long ev = 0, key[KEY_MAX / 64 + 1];
    850 	struct input_absinfo a;
    851 	struct dirent *e;
    852 	char path[300];
    853 	DIR *d = opendir("/dev/input");
    854 	int fd;
    855 
    856 	if (!d)
    857 		die("/dev/input");
    858 	while ((e = readdir(d)) && ndev < MAXDEV) {
    859 		if (strncmp(e->d_name, "event", 5))
    860 			continue;
    861 		snprintf(path, sizeof path, "/dev/input/%s", e->d_name);
    862 		if ((fd = open(path, O_RDONLY | O_NONBLOCK)) < 0)
    863 			continue;
    864 		memset(key, 0, sizeof key);
    865 		ioctl(fd, EVIOCGBIT(0, sizeof ev), &ev);
    866 		ioctl(fd, EVIOCGBIT(EV_KEY, sizeof key), key);
    867 		if (!(ev & (1 << EV_KEY))) {
    868 			close(fd);
    869 			continue;
    870 		}
    871 		dev[ndev].fd = fd;
    872 		dev[ndev].kbd = !!(key[KEY_A / 64] & 1UL << (KEY_A % 64));
    873 		if (ev & (1 << EV_ABS)) {
    874 			if (ioctl(fd, EVIOCGABS(ABS_X), &a) == 0)
    875 				dev[ndev].ax[0] = a.minimum, dev[ndev].ax[1] = a.maximum;
    876 			if (ioctl(fd, EVIOCGABS(ABS_Y), &a) == 0)
    877 				dev[ndev].ay[0] = a.minimum, dev[ndev].ay[1] = a.maximum;
    878 		}
    879 		ioctl(fd, EVIOCGRAB, 1);
    880 		ndev++;
    881 	}
    882 	closedir(d);
    883 }
    884 
    885 static void
    886 type(int code)
    887 {
    888 	static const struct { int code; char *s; } seq[] = {
    889 		{ KEY_UP, "\033[A" }, { KEY_DOWN, "\033[B" }, { KEY_RIGHT, "\033[C" }, { KEY_LEFT, "\033[D" },
    890 		{ KEY_HOME, "\033[1~" }, { KEY_INSERT, "\033[2~" }, { KEY_DELETE, "\033[3~" }, { KEY_END, "\033[4~" },
    891 		{ KEY_PAGEUP, "\033[5~" }, { KEY_PAGEDOWN, "\033[6~" }, { KEY_KPENTER, "\r" },
    892 		{ KEY_F1, "\033[[A" }, { KEY_F2, "\033[[B" }, { KEY_F3, "\033[[C" }, { KEY_F4, "\033[[D" },
    893 		{ KEY_F5, "\033[[E" },
    894 	};
    895 	Term *t = focused();
    896 	char c, buf[2];
    897 	unsigned i;
    898 
    899 	for (i = 0; i < LEN(seq); i++)
    900 		if (seq[i].code == code) {
    901 			reply(t, seq[i].s);
    902 			return;
    903 		}
    904 	if (code >= (int)sizeof keys - 1 || !(c = (shift ? shiftkeys : keys)[code]))
    905 		return;
    906 	if (caps && c >= 'a' && c <= 'z')
    907 		c -= 32;
    908 	else if (caps && c >= 'A' && c <= 'Z')
    909 		c += 32;
    910 	if (ctrl && c >= '@' && c <= '~')
    911 		c &= 0x1f;
    912 	else if (ctrl && c == ' ')
    913 		c = 0;
    914 	buf[0] = 033, buf[1] = c;
    915 	write(t->fd, alt ? buf : buf + 1, alt ? 2 : 1);
    916 }
    917 
    918 static void
    919 superkey(int code)
    920 {
    921 	if (code >= KEY_1 && code <= KEY_9) {
    922 		if (shift)
    923 			sendwin(code - KEY_1);
    924 		else
    925 			view(code - KEY_1);
    926 	} else if (code == KEY_ENTER)
    927 		newwin();
    928 	else if (code == KEY_Q && sel)
    929 		closewin(sel);
    930 	else if (code == KEY_TAB)
    931 		nextwin();
    932 	else if (code == KEY_F && sel)
    933 		fullscreen(sel);
    934 	else if (code == KEY_E && shift)
    935 		running = 0;
    936 }
    937 
    938 static Win *
    939 winat(int x, int y)
    940 {
    941 	Win *w, *hit = NULL;
    942 
    943 	for (w = wins; w; w = w->next)
    944 		if (w->scr == cur && x >= w->x && x < w->x + w->w && y >= w->y && y < w->y + w->h)
    945 			hit = w;
    946 	return hit;
    947 }
    948 
    949 static void
    950 click(int button)
    951 {
    952 	int x = mx / fw, y = my / fh;
    953 	Win *w = winat(x, y);
    954 
    955 	if (!w) {
    956 		sel = NULL;
    957 		return;
    958 	}
    959 	raise_(w);
    960 	if (!w->full && y == w->y && x >= w->x + w->w - 4 && x < w->x + w->w - 1) {
    961 		closewin(w);
    962 		return;
    963 	}
    964 	if (w->full)
    965 		return;
    966 	if ((super && (button == BTN_LEFT || button == BTN_RIGHT)) || y == w->y) {
    967 		drag = w, dragrs = super && button == BTN_RIGHT;
    968 		dragx = x, dragy = y;
    969 	}
    970 }
    971 
    972 static void
    973 motion(void)
    974 {
    975 	int x = mx / fw, y = my / fh;
    976 
    977 	if (!drag || (x == dragx && y == dragy))
    978 		return;
    979 	if (dragrs) {
    980 		drag->w = MAX(drag->w + x - dragx, 12);
    981 		drag->h = MAX(drag->h + y - dragy, 4);
    982 		fit(drag);
    983 	} else
    984 		drag->x += x - dragx, drag->y += y - dragy;
    985 	dragx = x, dragy = y;
    986 }
    987 
    988 static void
    989 input(Dev *d)
    990 {
    991 	struct input_event ev[64];
    992 	int n, i, moved = 0;
    993 
    994 	while ((n = read(d->fd, ev, sizeof ev)) > 0) {
    995 		for (i = 0; i < n / (int)sizeof *ev; i++) {
    996 			struct input_event *e = &ev[i];
    997 			if (e->type == EV_REL && e->code == REL_X)
    998 				mx += e->value, moved = 1;
    999 			else if (e->type == EV_REL && e->code == REL_Y)
   1000 				my += e->value, moved = 1;
   1001 			else if (e->type == EV_ABS && e->code == ABS_X && d->ax[1] > d->ax[0])
   1002 				mx = (long)(e->value - d->ax[0]) * fbw / (d->ax[1] - d->ax[0] + 1), moved = 1;
   1003 			else if (e->type == EV_ABS && e->code == ABS_Y && d->ay[1] > d->ay[0])
   1004 				my = (long)(e->value - d->ay[0]) * fbh / (d->ay[1] - d->ay[0] + 1), moved = 1;
   1005 			else if (e->type == EV_KEY && e->code >= BTN_MOUSE && e->code < BTN_JOYSTICK) {
   1006 				if (e->value == 1)
   1007 					click(e->code);
   1008 				else if (e->value == 0)
   1009 					drag = NULL;
   1010 			} else if (e->type == EV_KEY) {
   1011 				int down = e->value != 0;
   1012 				switch (e->code) {
   1013 				case KEY_LEFTSHIFT: case KEY_RIGHTSHIFT: shift = down; break;
   1014 				case KEY_LEFTCTRL: case KEY_RIGHTCTRL: ctrl = down; break;
   1015 				case KEY_LEFTALT: case KEY_RIGHTALT: alt = down; break;
   1016 				case KEY_LEFTMETA: case KEY_RIGHTMETA: super = down; break;
   1017 				case KEY_CAPSLOCK: if (e->value == 1) caps = !caps; break;
   1018 				default:
   1019 					if (down)
   1020 						super ? superkey(e->code) : type(e->code);
   1021 				}
   1022 			}
   1023 			dirty = 1;
   1024 		}
   1025 		if (moved) {
   1026 			mx = MAX(0, MIN(mx, cols * fw - 1));
   1027 			my = MAX(0, MIN(my, rows * fh - 1));
   1028 			motion();
   1029 		}
   1030 	}
   1031 }
   1032 
   1033 /* ---- the loop ---- */
   1034 static void
   1035 quit(int sig)
   1036 {
   1037 	(void)sig;
   1038 	running = 0;
   1039 }
   1040 
   1041 static int
   1042 output(Term *t)
   1043 {
   1044 	unsigned char buf[8192];
   1045 	int n;
   1046 
   1047 	while ((n = read(t->fd, buf, sizeof buf)) > 0)
   1048 		tfeed(t, buf, n);
   1049 	dirty = 1;
   1050 	return n == 0 || (n < 0 && errno != EAGAIN);
   1051 }
   1052 
   1053 int
   1054 main(void)
   1055 {
   1056 	struct pollfd pf[MAXDEV + NSCR + 256];
   1057 	Term *who[LEN(pf)];
   1058 	Win *w, *next;
   1059 	int i, n, nd;
   1060 
   1061 	sh = getenv("SHELL");
   1062 	if (!sh || access(sh, X_OK))
   1063 		sh = access("/sh", X_OK) == 0 ? "/sh" : "/bin/sh";
   1064 	/* the console it's started from: that one is yours. /dev/tty0 is root's */
   1065 	tty = 0;
   1066 	if (ioctl(tty, KDGETMODE, &i) < 0 && (tty = open("/dev/tty0", O_RDWR)) < 0)
   1067 		die("not on a console");
   1068 	getfont();
   1069 	openfb();
   1070 	opendevs();
   1071 	signal(SIGCHLD, SIG_DFL);
   1072 	signal(SIGTERM, quit);
   1073 	signal(SIGINT, quit);
   1074 	signal(SIGHUP, quit);
   1075 	ioctl(tty, KDSETMODE, KD_GRAPHICS);
   1076 	mx = fbw / 2, my = fbh / 2;
   1077 	view(0);
   1078 
   1079 	while (running) {
   1080 		if (dirty)
   1081 			draw();
   1082 		n = 0;
   1083 		for (i = 0; i < ndev; i++)
   1084 			pf[n].fd = dev[i].fd, pf[n].events = POLLIN, who[n++] = NULL;
   1085 		nd = n;
   1086 		for (i = 0; i < NSCR; i++)
   1087 			if (shell[i].pid)
   1088 				pf[n].fd = shell[i].fd, pf[n].events = POLLIN, who[n++] = &shell[i];
   1089 		for (w = wins; w && n < (int)LEN(pf); w = w->next)
   1090 			pf[n].fd = w->t.fd, pf[n].events = POLLIN, who[n++] = &w->t;
   1091 		if (poll(pf, n, 1000) == 0) {
   1092 			dirty = 1;
   1093 			continue;
   1094 		}
   1095 		for (i = 0; i < nd; i++)
   1096 			if (pf[i].revents)
   1097 				input(&dev[i]);
   1098 		for (i = nd; i < n; i++) {
   1099 			if (!pf[i].revents || !output(who[i]))
   1100 				continue;
   1101 			/* its shell has gone: a screen gets a new one, a window closes */
   1102 			if (who[i] >= shell && who[i] < shell + NSCR) {
   1103 				tfree(who[i]);
   1104 				tnew(who[i], cols, rows - 1);
   1105 			} else
   1106 				for (w = wins; w; w = next) {
   1107 					next = w->next;
   1108 					if (&w->t == who[i])
   1109 						closewin(w);
   1110 				}
   1111 			/* the pollfd array still points at what's gone: start again */
   1112 			break;
   1113 		}
   1114 		while (waitpid(-1, NULL, WNOHANG) > 0)
   1115 			;
   1116 	}
   1117 	for (i = 0; i < NSCR; i++)
   1118 		if (shell[i].pid)
   1119 			tfree(&shell[i]);
   1120 	while (wins)
   1121 		closewin(wins);
   1122 	ioctl(tty, KDSETMODE, KD_TEXT);
   1123 	return 0;
   1124 }