chamesle

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

tyrmel.c (56546B)


      1 /* tyrmel - a terminal that looks like the console and shows pictures like kitty */
      2 #include <ctype.h>
      3 #include <errno.h>
      4 #include <fcntl.h>
      5 #include <limits.h>
      6 #include <locale.h>
      7 #include <pty.h>
      8 #include <signal.h>
      9 #include <stdint.h>
     10 #include <stdio.h>
     11 #include <stdlib.h>
     12 #include <string.h>
     13 #include <time.h>
     14 #include <unistd.h>
     15 #include <sys/ioctl.h>
     16 #include <sys/select.h>
     17 #include <sys/stat.h>
     18 #include <sys/wait.h>
     19 #include <X11/Xatom.h>
     20 #include <X11/Xlib.h>
     21 #include <X11/Xutil.h>
     22 #include <X11/XKBlib.h>
     23 #include <X11/keysym.h>
     24 #include <X11/extensions/Xrender.h>
     25 #include <X11/Xft/Xft.h>
     26 #include <fontconfig/fontconfig.h>
     27 #include <png.h>
     28 #include <zlib.h>
     29 #include <vterm.h>
     30 
     31 #define LENGTH(X)       (sizeof(X) / sizeof(X)[0])
     32 #define MIN(A, B)       ((A) < (B) ? (A) : (B))
     33 #define MAX(A, B)       ((A) > (B) ? (A) : (B))
     34 #define MAXIMAGES       64
     35 #define MAXPLACES       256
     36 #define MAXFALLBACK     32
     37 #define MAXAPC          (256 << 20)
     38 
     39 /* a line of the scrollback: only what's needed to draw it again */
     40 typedef struct {
     41 	uint32_t ch;
     42 	uint8_t fg[3], bg[3];
     43 	uint8_t flags, width;
     44 } Cell;
     45 enum { FBold = 1, FUnder = 2, FReverse = 4, FStrike = 8, FDefFg = 16, FDefBg = 32 };
     46 
     47 typedef struct {
     48 	int cols;
     49 	Cell *cells;
     50 } Line;
     51 
     52 /* pictures sent with kitty's graphics protocol */
     53 typedef struct {
     54 	unsigned int id;
     55 	int w, h;
     56 	uint32_t *argb;	/* premultiplied */
     57 } Image;
     58 
     59 typedef struct {
     60 	Image *img;
     61 	unsigned int id, pid;
     62 	long line;	/* counted from the top of the scrollback, so it scrolls with the text */
     63 	int col, cols, rows, alt, z;
     64 	int sx, sy, sw, sh;	/* the part of the image shown */
     65 	Picture pic;
     66 	int pw, ph;
     67 } Place;
     68 
     69 typedef struct {
     70 	XftFont *font;
     71 	FcFontSet *set;
     72 	FcPattern *pat;
     73 	struct { XftFont *font; uint32_t ch; } fb[MAXFALLBACK];
     74 	int nfb;
     75 } Fonts;
     76 
     77 /* settings, from ~/.config/tyrmel/config */
     78 static char fontname[256] = "VGA";
     79 static int fontsize = 16, scrollmax = 10000, cursorshape = 1;
     80 static char shellcmd[512], bgname[32] = "black", fgname[32] = "grey", cursorname[32] = "grey";
     81 static char palname[16][32];
     82 
     83 static const char defaultconfig[] =
     84 "# tyrmel settings\n"
     85 "# change what's after the = and save. it works straight away\n"
     86 "\n"
     87 "font = VGA\n"
     88 "font size = 16\n"
     89 "# lines you can scroll back. shift+page up, or the mouse wheel\n"
     90 "scrollback = 10000\n"
     91 "# block, underline or bar\n"
     92 "cursor = block\n"
     93 "# what runs in it. nothing means your login shell\n"
     94 "shell =\n"
     95 "\n"
     96 "# colours: black blue green cyan red magenta brown grey\n"
     97 "#          dark grey, light blue, light green, light cyan, light red, pink, yellow, white\n"
     98 "#          or #rrggbb\n"
     99 "background colour = black\n"
    100 "text colour = grey\n"
    101 "cursor colour = grey\n"
    102 "# the 16 colours programs use, if you want others:\n"
    103 "# colour 1 = #aa0000\n"
    104 "\n"
    105 "# keys: ctrl+shift+c copy, ctrl+shift+v paste, shift+insert paste the selection,\n"
    106 "# shift+page up and down scroll, ctrl+shift+plus and minus the font size, ctrl+shift+0 back.\n"
    107 "# ctrl+click an address to open it\n";
    108 
    109 static const char *vgahex[16] = {
    110 	"#000000", "#aa0000", "#00aa00", "#aa5500", "#0000aa", "#aa00aa", "#00aaaa", "#aaaaaa",
    111 	"#555555", "#ff5555", "#55ff55", "#ffff55", "#5555ff", "#ff55ff", "#55ffff", "#ffffff",
    112 };
    113 
    114 static Display *dpy;
    115 static Window win;
    116 static Visual *vis;
    117 static Colormap cmap;
    118 static int scr, depth;
    119 static Pixmap buf;
    120 static Picture bufpic;
    121 static XftDraw *draw;
    122 static GC gc;
    123 static XIM xim;
    124 static XIC xic;
    125 static Atom wmdelete, xclipboard, xtargets, xutf8, xprop, netwmname, netwmpid;
    126 static Fonts fonts;
    127 static int cw, ch, ascent, rows = 24, cols = 80, ww, wh;
    128 static int basesize, samewidth;	/* samewidth: the font's letters are a cell wide, so they can go in runs */
    129 
    130 static VTerm *vt;
    131 static VTermScreen *vs;
    132 static VTermState *vst;
    133 static int ptyfd = -1;
    134 static pid_t child;
    135 
    136 static Line *sb;	/* scrollback ring */
    137 static int sbn, sbhead;
    138 static long scrolled;	/* lines that ever went into the scrollback */
    139 static int view;	/* how far back you're looking */
    140 static int alt, cursorvisible = 1, focused = 1, mousemode;
    141 static VTermPos cursor;
    142 static int dirty = 1;
    143 
    144 static Image *images[MAXIMAGES];
    145 static int nimages;
    146 static Place places[MAXPLACES];
    147 static int nplaces;
    148 static char *apc;
    149 static size_t apclen, apcsize;
    150 static int pendingrows, pendingcols;
    151 
    152 /* selection, in rows counted from the top of the scrollback */
    153 static struct { long r0, r1; int c0, c1, on, going; } sel;
    154 static char *seltext;
    155 static Time lastclick;
    156 static int clicks;
    157 
    158 static char cfgpath[1100];
    159 static time_t cfgmtime;
    160 static const char *wclass = "tyrmel", *wname = "tyrmel", *wtitle;
    161 static char **cmdargv;
    162 static int geomcols = 80, geomrows = 24, holdopen, forcesize;	/* forcesize: -fs, over the settings */
    163 
    164 /* ---- small things ---- */
    165 
    166 static void
    167 die(const char *msg)
    168 {
    169 	fprintf(stderr, "tyrmel: %s\n", msg);
    170 	exit(1);
    171 }
    172 
    173 static char *
    174 trim(char *s)
    175 {
    176 	char *e;
    177 
    178 	while (isspace((unsigned char)*s))
    179 		s++;
    180 	for (e = s + strlen(s); e > s && isspace((unsigned char)e[-1]); e--);
    181 	*e = '\0';
    182 	return s;
    183 }
    184 
    185 static void
    186 squash(char *dst, const char *src, size_t n)
    187 {
    188 	size_t i = 0;
    189 
    190 	for (; *src && i < n - 1; src++)
    191 		if (!isspace((unsigned char)*src))
    192 			dst[i++] = tolower((unsigned char)*src);
    193 	dst[i] = '\0';
    194 }
    195 
    196 static int
    197 parsecolour(const char *name, uint8_t rgb[3])
    198 {
    199 	static const char *names[][2] = {
    200 		{ "black", "#000000" }, { "blue", "#0000aa" }, { "green", "#00aa00" }, { "cyan", "#00aaaa" },
    201 		{ "red", "#aa0000" }, { "magenta", "#aa00aa" }, { "brown", "#aa5500" }, { "grey", "#aaaaaa" },
    202 		{ "gray", "#aaaaaa" }, { "darkgrey", "#555555" }, { "darkgray", "#555555" },
    203 		{ "lightblue", "#5555ff" }, { "lightgreen", "#55ff55" }, { "lightcyan", "#55ffff" },
    204 		{ "lightred", "#ff5555" }, { "pink", "#ff55ff" }, { "yellow", "#ffff55" }, { "white", "#ffffff" },
    205 	};
    206 	char s[32];
    207 	const char *hex = NULL;
    208 	unsigned int i, v;
    209 
    210 	squash(s, name, sizeof s);
    211 	for (i = 0; i < LENGTH(names); i++)
    212 		if (!strcmp(s, names[i][0]))
    213 			hex = names[i][1];
    214 	if (!hex && s[0] == '#')
    215 		hex = s;
    216 	if (!hex || strlen(hex) != 7 || sscanf(hex + 1, "%x", &v) != 1)
    217 		return 0;
    218 	rgb[0] = v >> 16, rgb[1] = v >> 8, rgb[2] = v;
    219 	return 1;
    220 }
    221 
    222 static void
    223 xcolour(const uint8_t rgb[3], XftColor *c)
    224 {
    225 	XRenderColor r = { rgb[0] * 257, rgb[1] * 257, rgb[2] * 257, 0xffff };
    226 
    227 	XftColorAllocValue(dpy, vis, cmap, &r, c);
    228 }
    229 
    230 static void
    231 writepty(const char *s, size_t n)
    232 {
    233 	ssize_t r;
    234 
    235 	while (n > 0) {
    236 		r = write(ptyfd, s, n);
    237 		if (r < 0) {
    238 			if (errno == EINTR || errno == EAGAIN)
    239 				continue;
    240 			return;
    241 		}
    242 		s += r, n -= r;
    243 	}
    244 }
    245 
    246 static long
    247 ms(void)
    248 {
    249 	struct timespec ts;
    250 
    251 	clock_gettime(CLOCK_MONOTONIC, &ts);
    252 	return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
    253 }
    254 
    255 /* ---- settings ---- */
    256 
    257 static void
    258 loadconfig(void)
    259 {
    260 	char line[1024], key[64], *name, *value, *eq;
    261 	struct stat st;
    262 	FILE *f;
    263 	int i;
    264 
    265 	if (stat(cfgpath, &st) < 0 && (f = fopen(cfgpath, "w"))) {
    266 		fputs(defaultconfig, f);
    267 		fclose(f);
    268 	}
    269 	if (stat(cfgpath, &st) == 0)
    270 		cfgmtime = st.st_mtime;
    271 	for (i = 0; i < 16; i++)
    272 		palname[i][0] = '\0';
    273 	if (!(f = fopen(cfgpath, "r")))
    274 		return;
    275 	while (fgets(line, sizeof line, f)) {
    276 		if (*trim(line) == '#' || !(eq = strchr(line, '=')))
    277 			continue;
    278 		*eq = '\0';
    279 		name = trim(line);
    280 		value = trim(eq + 1);
    281 		squash(key, name, sizeof key);
    282 		if (!strcmp(key, "font"))
    283 			snprintf(fontname, sizeof fontname, "%s", *value ? value : "VGA");
    284 		else if (!strcmp(key, "fontsize"))
    285 			fontsize = atoi(value) > 3 ? atoi(value) : 16;
    286 		else if (!strcmp(key, "scrollback"))
    287 			scrollmax = MAX(atoi(value), 0);
    288 		else if (!strcmp(key, "cursor")) {
    289 			squash(key, value, sizeof key);
    290 			cursorshape = !strcmp(key, "underline") ? VTERM_PROP_CURSORSHAPE_UNDERLINE :
    291 			              !strcmp(key, "bar") ? VTERM_PROP_CURSORSHAPE_BAR_LEFT : VTERM_PROP_CURSORSHAPE_BLOCK;
    292 		} else if (!strcmp(key, "shell"))
    293 			snprintf(shellcmd, sizeof shellcmd, "%s", value);
    294 		else if (!strcmp(key, "backgroundcolour") || !strcmp(key, "backgroundcolor"))
    295 			snprintf(bgname, sizeof bgname, "%s", value);
    296 		else if (!strcmp(key, "textcolour") || !strcmp(key, "textcolor"))
    297 			snprintf(fgname, sizeof fgname, "%s", value);
    298 		else if (!strcmp(key, "cursorcolour") || !strcmp(key, "cursorcolor"))
    299 			snprintf(cursorname, sizeof cursorname, "%s", value);
    300 		else if ((!strncmp(key, "colour", 6) || !strncmp(key, "color", 5))
    301 		     && (i = atoi(key + (key[4] == 'u' ? 6 : 5))) >= 0 && i < 16 && isdigit((unsigned char)key[key[4] == 'u' ? 6 : 5]))
    302 			snprintf(palname[i], sizeof palname[i], "%s", value);
    303 		else
    304 			fprintf(stderr, "tyrmel: %s: don't know '%s'\n", cfgpath, name);
    305 	}
    306 	fclose(f);
    307 }
    308 
    309 static void
    310 setcolours(void)
    311 {
    312 	VTermColor fg, bg, c;
    313 	uint8_t rgb[3];
    314 	int i;
    315 
    316 	for (i = 0; i < 16; i++) {
    317 		if (!parsecolour(palname[i][0] ? palname[i] : vgahex[i], rgb))
    318 			parsecolour(vgahex[i], rgb);
    319 		vterm_color_rgb(&c, rgb[0], rgb[1], rgb[2]);
    320 		vterm_state_set_palette_color(vst, i, &c);
    321 	}
    322 	if (!parsecolour(fgname, rgb))
    323 		parsecolour("grey", rgb);
    324 	vterm_color_rgb(&fg, rgb[0], rgb[1], rgb[2]);
    325 	if (!parsecolour(bgname, rgb))
    326 		parsecolour("black", rgb);
    327 	vterm_color_rgb(&bg, rgb[0], rgb[1], rgb[2]);
    328 	vterm_screen_set_default_colors(vs, &fg, &bg);
    329 	dirty = 1;
    330 }
    331 
    332 /* ---- fonts: the one you picked, and others for what it hasn't got ---- */
    333 
    334 static void
    335 unloadfonts(void)
    336 {
    337 	int i;
    338 
    339 	for (i = 0; i < fonts.nfb; i++)
    340 		XftFontClose(dpy, fonts.fb[i].font);
    341 	fonts.nfb = 0;
    342 	if (fonts.font)
    343 		XftFontClose(dpy, fonts.font);
    344 	if (fonts.set)
    345 		FcFontSetDestroy(fonts.set);
    346 	if (fonts.pat)
    347 		FcPatternDestroy(fonts.pat);
    348 	memset(&fonts, 0, sizeof fonts);
    349 }
    350 
    351 static void
    352 loadfonts(int size)
    353 {
    354 	FcPattern *pat, *match;
    355 	FcResult r;
    356 	char name[300];
    357 
    358 	unloadfonts();
    359 	snprintf(name, sizeof name, "%s:pixelsize=%d", fontname, size);
    360 	if (!(pat = FcNameParse((FcChar8 *)name)))
    361 		die("can't read the font name");
    362 	FcConfigSubstitute(NULL, pat, FcMatchPattern);
    363 	XftDefaultSubstitute(dpy, scr, pat);
    364 	if (!(match = FcFontMatch(NULL, pat, &r)) || !(fonts.font = XftFontOpenPattern(dpy, match))) {
    365 		if (!(fonts.font = XftFontOpenName(dpy, scr, "monospace:pixelsize=16")))
    366 			die("no font");
    367 	}
    368 	fonts.pat = pat;
    369 	cw = fonts.font->max_advance_width;
    370 	ch = fonts.font->ascent + fonts.font->descent;
    371 	ascent = fonts.font->ascent;
    372 	/* a monospace font's widest glyph is its cell, but some lie */
    373 	{
    374 		XGlyphInfo gi;
    375 
    376 		XftTextExtentsUtf8(dpy, fonts.font, (FcChar8 *)"M", 1, &gi);
    377 		if (gi.xOff > 0 && gi.xOff < cw)
    378 			cw = gi.xOff;
    379 		samewidth = gi.xOff == cw;
    380 	}
    381 }
    382 
    383 static int
    384 pua(uint32_t c)
    385 {
    386 	return (c >= 0xe000 && c <= 0xf8ff) || c >= 0xf0000;
    387 }
    388 
    389 static XftFont *
    390 fontfor(uint32_t c)
    391 {
    392 	static uint32_t missing[64];
    393 	static unsigned int nmissing;
    394 	FcCharSet *cs;
    395 	FcPattern *m;
    396 	FcChar8 *mine = NULL, *fam;
    397 	FcResult r;
    398 	int i, pass;
    399 
    400 	/* the private use area is icons: fonts that aren't made for them only pretend */
    401 	if (!pua(c) && XftCharExists(dpy, fonts.font, c))
    402 		return fonts.font;
    403 	for (i = 0; i < fonts.nfb; i++)
    404 		if (fonts.fb[i].ch == c || XftCharExists(dpy, fonts.fb[i].font, c))
    405 			return fonts.fb[i].font;
    406 	/* no font has it: don't look again every frame */
    407 	for (i = 0; i < (int)LENGTH(missing); i++)
    408 		if (missing[i] == c)
    409 			return fonts.font;
    410 	if (!fonts.set)
    411 		fonts.set = FcFontSort(NULL, fonts.pat, 1, NULL, &r);
    412 	/* the closest font to yours that has it, but not yours. icons from a nerd font if there is one */
    413 	m = NULL;
    414 	FcPatternGetString(fonts.font->pattern, FC_FAMILY, 0, &mine);
    415 	for (pass = pua(c) ? 0 : 1; !m && pass < 2; pass++)
    416 		for (i = 0; fonts.set && i < fonts.set->nfont; i++) {
    417 			if (FcPatternGetCharSet(fonts.set->fonts[i], FC_CHARSET, 0, &cs) != FcResultMatch || !FcCharSetHasChar(cs, c))
    418 				continue;
    419 			if (FcPatternGetString(fonts.set->fonts[i], FC_FAMILY, 0, &fam) != FcResultMatch)
    420 				continue;
    421 			if ((mine && !strcmp((char *)fam, (char *)mine)) || (pass == 0 && !strstr((char *)fam, "Nerd")))
    422 				continue;
    423 			m = FcFontRenderPrepare(NULL, fonts.pat, fonts.set->fonts[i]);
    424 			break;
    425 		}
    426 	if (!m) {
    427 		missing[nmissing++ % LENGTH(missing)] = c;
    428 		return fonts.font;
    429 	}
    430 	if (fonts.nfb == MAXFALLBACK) {
    431 		XftFontClose(dpy, fonts.fb[0].font);
    432 		memmove(fonts.fb, fonts.fb + 1, (MAXFALLBACK - 1) * sizeof fonts.fb[0]);
    433 		fonts.nfb--;
    434 	}
    435 	fonts.fb[fonts.nfb].font = XftFontOpenPattern(dpy, m);
    436 	fonts.fb[fonts.nfb].ch = c;
    437 	if (!fonts.fb[fonts.nfb].font) {
    438 		FcPatternDestroy(m);
    439 		return fonts.font;
    440 	}
    441 	return fonts.fb[fonts.nfb++].font;
    442 }
    443 
    444 /* ---- the scrollback ---- */
    445 
    446 static Line *
    447 sbline(int i)	/* 0 is the oldest */
    448 {
    449 	return &sb[(sbhead + i) % scrollmax];
    450 }
    451 
    452 static void
    453 tocell(const VTermScreenCell *v, Cell *c)
    454 {
    455 	VTermColor fg = v->fg, bg = v->bg;
    456 
    457 	c->ch = v->chars[0];
    458 	c->width = v->width;
    459 	c->flags = (v->attrs.bold ? FBold : 0) | (v->attrs.underline ? FUnder : 0) |
    460 	           (v->attrs.reverse ? FReverse : 0) | (v->attrs.strike ? FStrike : 0) |
    461 	           (VTERM_COLOR_IS_DEFAULT_FG(&fg) ? FDefFg : 0) | (VTERM_COLOR_IS_DEFAULT_BG(&bg) ? FDefBg : 0);
    462 	vterm_screen_convert_color_to_rgb(vs, &fg);
    463 	vterm_screen_convert_color_to_rgb(vs, &bg);
    464 	c->fg[0] = fg.rgb.red, c->fg[1] = fg.rgb.green, c->fg[2] = fg.rgb.blue;
    465 	c->bg[0] = bg.rgb.red, c->bg[1] = bg.rgb.green, c->bg[2] = bg.rgb.blue;
    466 }
    467 
    468 static void
    469 dropplaces(void)
    470 {
    471 	int i, j;
    472 
    473 	/* pictures that went off the top of the scrollback */
    474 	for (i = j = 0; i < nplaces; i++) {
    475 		if (!places[i].alt && places[i].line + places[i].rows < scrolled - sbn) {
    476 			if (places[i].pic)
    477 				XRenderFreePicture(dpy, places[i].pic);
    478 			continue;
    479 		}
    480 		places[j++] = places[i];
    481 	}
    482 	nplaces = j;
    483 }
    484 
    485 static int
    486 sbpush(int n, const VTermScreenCell *cells, void *user)
    487 {
    488 	Line *l;
    489 	int i;
    490 
    491 	scrolled++;
    492 	if (!scrollmax) {
    493 		if (sel.on)
    494 			sel.r0--, sel.r1--;
    495 		return 1;
    496 	}
    497 	/* keep only up to the last thing on the line */
    498 	while (n > 0 && !cells[n - 1].chars[0] && VTERM_COLOR_IS_DEFAULT_BG(&cells[n - 1].bg))
    499 		n--;
    500 	if (sbn == scrollmax) {
    501 		l = sbline(0);
    502 		free(l->cells);
    503 		sbhead = (sbhead + 1) % scrollmax;
    504 		sbn--;
    505 		if (sel.on)
    506 			sel.r0--, sel.r1--;
    507 	}
    508 	l = sbline(sbn++);
    509 	l->cols = n;
    510 	l->cells = n ? malloc(n * sizeof *l->cells) : NULL;
    511 	for (i = 0; i < n; i++)
    512 		tocell(&cells[i], &l->cells[i]);
    513 	dropplaces();
    514 	if (view)
    515 		view = MIN(view + 1, sbn);
    516 	dirty = 1;
    517 	return 1;
    518 }
    519 
    520 static int
    521 sbpop(int n, VTermScreenCell *cells, void *user)
    522 {
    523 	Line *l;
    524 	int i;
    525 
    526 	if (!sbn)
    527 		return 0;
    528 	l = sbline(--sbn);
    529 	scrolled--;
    530 	for (i = 0; i < n; i++) {
    531 		memset(&cells[i], 0, sizeof cells[i]);
    532 		cells[i].width = 1;
    533 		vterm_state_get_default_colors(vst, &cells[i].fg, &cells[i].bg);
    534 		if (i < l->cols) {
    535 			cells[i].chars[0] = l->cells[i].ch;
    536 			cells[i].width = l->cells[i].width ? l->cells[i].width : 1;
    537 			cells[i].attrs.bold = !!(l->cells[i].flags & FBold);
    538 			cells[i].attrs.underline = !!(l->cells[i].flags & FUnder);
    539 			cells[i].attrs.reverse = !!(l->cells[i].flags & FReverse);
    540 			cells[i].attrs.strike = !!(l->cells[i].flags & FStrike);
    541 			if (!(l->cells[i].flags & FDefFg))
    542 				vterm_color_rgb(&cells[i].fg, l->cells[i].fg[0], l->cells[i].fg[1], l->cells[i].fg[2]);
    543 			if (!(l->cells[i].flags & FDefBg))
    544 				vterm_color_rgb(&cells[i].bg, l->cells[i].bg[0], l->cells[i].bg[1], l->cells[i].bg[2]);
    545 		}
    546 	}
    547 	free(l->cells);
    548 	l->cells = NULL;
    549 	dirty = 1;
    550 	return 1;
    551 }
    552 
    553 /* the scrollback setting changed while running: the lines that fit go into a ring of the new size */
    554 static void
    555 setscrollback(int n)
    556 {
    557 	Line *nsb = n ? calloc(n, sizeof *nsb) : NULL;
    558 	int keep = MIN(sbn, n), i;
    559 
    560 	if (n && !nsb)
    561 		return;
    562 	for (i = 0; i < sbn; i++) {
    563 		if (i < sbn - keep)
    564 			free(sbline(i)->cells);
    565 		else
    566 			nsb[i - (sbn - keep)] = *sbline(i);
    567 	}
    568 	free(sb);
    569 	sb = nsb;
    570 	sbhead = 0;
    571 	sbn = keep;
    572 	scrollmax = n;
    573 	view = MIN(view, sbn);
    574 	sel.on = 0;
    575 	dropplaces();
    576 	dirty = 1;
    577 }
    578 
    579 static int
    580 sbclear(void *user)
    581 {
    582 	while (sbn)
    583 		free(sbline(--sbn)->cells);
    584 	view = 0;
    585 	dirty = 1;
    586 	return 1;
    587 }
    588 
    589 /* row r of what's on the window, as cells. scrollback or screen */
    590 static int
    591 viewrow(int r, Cell *out)
    592 {
    593 	VTermScreenCell v;
    594 	VTermPos p;
    595 	Line *l;
    596 	int c;
    597 
    598 	if (r < view) {
    599 		l = sbline(sbn - view + r);
    600 		for (c = 0; c < cols; c++) {
    601 			if (c < l->cols)
    602 				out[c] = l->cells[c];
    603 			else {
    604 				memset(&out[c], 0, sizeof out[c]);
    605 				out[c].width = 1;
    606 				out[c].flags = FDefFg | FDefBg;
    607 			}
    608 		}
    609 		return 1;
    610 	}
    611 	p.row = r - view;
    612 	for (c = 0; c < cols; c++) {
    613 		p.col = c;
    614 		vterm_screen_get_cell(vs, p, &v);
    615 		tocell(&v, &out[c]);
    616 	}
    617 	return 0;
    618 }
    619 
    620 /* ---- pictures ---- */
    621 
    622 static int
    623 unbase64(const char *s, size_t n, unsigned char *out)
    624 {
    625 	static signed char t[256];
    626 	size_t i;
    627 	int bits = 0, len = 0, v;
    628 	unsigned int acc = 0;
    629 
    630 	if (!t['B']) {
    631 		memset(t, -1, sizeof t);
    632 		for (i = 0; i < 64; i++)
    633 			t[(unsigned char)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
    634 	}
    635 	for (i = 0; i < n; i++) {
    636 		if ((v = t[(unsigned char)s[i]]) < 0)
    637 			continue;
    638 		acc = acc << 6 | v;
    639 		if ((bits += 6) >= 8) {
    640 			bits -= 8;
    641 			out[len++] = acc >> bits;
    642 		}
    643 	}
    644 	return len;
    645 }
    646 
    647 static void
    648 freeimage(Image *im)
    649 {
    650 	int i, j;
    651 
    652 	for (i = j = 0; i < nplaces; i++) {
    653 		if (places[i].img == im) {
    654 			if (places[i].pic)
    655 				XRenderFreePicture(dpy, places[i].pic);
    656 			continue;
    657 		}
    658 		places[j++] = places[i];
    659 	}
    660 	nplaces = j;
    661 	for (i = j = 0; i < nimages; i++)
    662 		if (images[i] != im)
    663 			images[j++] = images[i];
    664 	nimages = j;
    665 	free(im->argb);
    666 	free(im);
    667 }
    668 
    669 static Image *
    670 findimage(unsigned int id)
    671 {
    672 	int i;
    673 
    674 	for (i = 0; id && i < nimages; i++)
    675 		if (images[i]->id == id)
    676 			return images[i];
    677 	return NULL;
    678 }
    679 
    680 static void
    681 delplace(int i)
    682 {
    683 	Image *im = places[i].img;
    684 	int j;
    685 
    686 	if (places[i].pic)
    687 		XRenderFreePicture(dpy, places[i].pic);
    688 	places[i] = places[--nplaces];
    689 	/* a picture without an id can't be shown again */
    690 	for (j = 0; j < nplaces; j++)
    691 		if (places[j].img == im)
    692 			return;
    693 	if (!im->id)
    694 		freeimage(im);
    695 }
    696 
    697 static uint32_t *
    698 loadpng(const unsigned char *data, size_t n, int *w, int *h)
    699 {
    700 	png_image pi;
    701 	uint32_t *px;
    702 
    703 	memset(&pi, 0, sizeof pi);
    704 	pi.version = PNG_IMAGE_VERSION;
    705 	if (!png_image_begin_read_from_memory(&pi, data, n))
    706 		return NULL;
    707 	pi.format = PNG_FORMAT_BGRA;
    708 	if (!(px = malloc(PNG_IMAGE_SIZE(pi)))) {
    709 		png_image_free(&pi);
    710 		return NULL;
    711 	}
    712 	if (!png_image_finish_read(&pi, NULL, px, 0, NULL)) {
    713 		free(px);
    714 		return NULL;
    715 	}
    716 	*w = pi.width, *h = pi.height;
    717 	return px;
    718 }
    719 
    720 /* the pixels the protocol sends, into premultiplied argb */
    721 static uint32_t *
    722 topixels(int fmt, unsigned char *data, size_t n, int *w, int *h)
    723 {
    724 	uint32_t *px, a, p;
    725 	size_t i, need;
    726 	int bpp = fmt == 24 ? 3 : 4;
    727 
    728 	if (fmt == 100) {
    729 		if (!(px = loadpng(data, n, w, h)))
    730 			return NULL;
    731 		for (i = 0; i < (size_t)*w * *h; i++) {
    732 			p = px[i], a = p >> 24;
    733 			px[i] = a << 24 | ((p >> 16 & 255) * a / 255) << 16 | ((p >> 8 & 255) * a / 255) << 8 | (p & 255) * a / 255;
    734 		}
    735 		return px;
    736 	}
    737 	need = (size_t)*w * *h * bpp;
    738 	if (*w <= 0 || *h <= 0 || n < need || !(px = malloc((size_t)*w * *h * 4)))
    739 		return NULL;
    740 	for (i = 0; i < (size_t)*w * *h; i++) {
    741 		a = bpp == 4 ? data[i * 4 + 3] : 255;
    742 		px[i] = a << 24 | (data[i * bpp] * a / 255) << 16 | (data[i * bpp + 1] * a / 255) << 8 | data[i * bpp + 2] * a / 255;
    743 	}
    744 	return px;
    745 }
    746 
    747 /* the picture at the size it's shown, as an xrender picture */
    748 static void
    749 makepic(Place *p)
    750 {
    751 	Image *im = p->img;
    752 	XImage *xi;
    753 	Pixmap pm;
    754 	GC pgc;
    755 	uint32_t *px;
    756 	int w, h, x, y, sx, sy;
    757 
    758 	w = p->cols * cw, h = p->rows * ch;
    759 	if (p->pic && p->pw == w && p->ph == h)
    760 		return;
    761 	if (p->pic)
    762 		XRenderFreePicture(dpy, p->pic);
    763 	p->pic = None;
    764 	/* shrink to fit the cells it was given, keeping its shape */
    765 	if (p->sw * h > p->sh * w)
    766 		h = MAX(1, (long)p->sh * w / p->sw);
    767 	else
    768 		w = MAX(1, (long)p->sw * h / p->sh);
    769 	/* a program asking for a picture a million cells wide gets one X can actually make */
    770 	if (w > 4096 || h > 4096) {
    771 		if (w >= h)
    772 			h = MAX(1, (long)h * 4096 / w), w = 4096;
    773 		else
    774 			w = MAX(1, (long)w * 4096 / h), h = 4096;
    775 	}
    776 	if (!(px = malloc((size_t)w * h * 4)))
    777 		return;
    778 	for (y = 0; y < h; y++) {
    779 		sy = p->sy + (long)y * p->sh / h;
    780 		for (x = 0; x < w; x++) {
    781 			sx = p->sx + (long)x * p->sw / w;
    782 			px[y * w + x] = im->argb[sy * im->w + sx];
    783 		}
    784 	}
    785 	pm = XCreatePixmap(dpy, win, w, h, 32);
    786 	pgc = XCreateGC(dpy, pm, 0, NULL);
    787 	xi = XCreateImage(dpy, vis, 32, ZPixmap, 0, (char *)px, w, h, 32, 0);
    788 	XPutImage(dpy, pm, pgc, xi, 0, 0, 0, 0, w, h);
    789 	XDestroyImage(xi);	/* frees px */
    790 	XFreeGC(dpy, pgc);
    791 	p->pic = XRenderCreatePicture(dpy, pm, XRenderFindStandardFormat(dpy, PictStandardARGB32), 0, NULL);
    792 	XFreePixmap(dpy, pm);
    793 	p->pw = p->cols * cw, p->ph = p->rows * ch;
    794 }
    795 
    796 static void
    797 reply(unsigned int id, unsigned int pid, int quiet, const char *msg)
    798 {
    799 	char s[256];
    800 	int n;
    801 
    802 	if (!id || quiet >= 2 || (quiet == 1 && !strcmp(msg, "OK")))
    803 		return;
    804 	n = pid ? snprintf(s, sizeof s, "\033_Gi=%u,p=%u;%s\033\\", id, pid, msg)
    805 	        : snprintf(s, sizeof s, "\033_Gi=%u;%s\033\\", id, msg);
    806 	writepty(s, n);
    807 }
    808 
    809 static void
    810 place(Image *im, unsigned int pid, int c, int r, int nomove, int z, int x, int y, int w, int h)
    811 {
    812 	Place *p;
    813 	int i;
    814 
    815 	/* the same picture and placement again replaces it */
    816 	for (i = 0; im->id && pid && i < nplaces; i++)
    817 		if (places[i].img == im && places[i].pid == pid) {
    818 			delplace(i);
    819 			break;
    820 		}
    821 	if (nplaces == MAXPLACES)
    822 		delplace(0);
    823 	p = &places[nplaces++];
    824 	memset(p, 0, sizeof *p);
    825 	p->img = im;
    826 	p->id = im->id;
    827 	p->pid = pid;
    828 	p->sx = MIN(MAX(x, 0), im->w - 1);
    829 	p->sy = MIN(MAX(y, 0), im->h - 1);
    830 	p->sw = w > 0 ? MIN(w, im->w - p->sx) : im->w - p->sx;
    831 	p->sh = h > 0 ? MIN(h, im->h - p->sy) : im->h - p->sy;
    832 	p->cols = c > 0 ? c : (p->sw + cw - 1) / cw;
    833 	p->rows = r > 0 ? r : (p->sh + ch - 1) / ch;
    834 	p->alt = alt;
    835 	p->z = z;
    836 	p->line = (alt ? 0 : scrolled) + cursor.row;
    837 	p->col = cursor.col;
    838 	if (!nomove) {
    839 		pendingrows = p->rows - 1;
    840 		pendingcols = p->cols;
    841 	}
    842 	dirty = 1;
    843 }
    844 
    845 static void
    846 delete(int what, unsigned int id, int x, int y)
    847 {
    848 	int i, all = isupper(what);
    849 	long line;
    850 	Image *im;
    851 
    852 	switch (tolower(what)) {
    853 	case 'i':
    854 		if ((im = findimage(id))) {
    855 			if (all)
    856 				freeimage(im);
    857 			else
    858 				for (i = nplaces - 1; i >= 0; i--)
    859 					if (places[i].img == im)
    860 						delplace(i);
    861 		}
    862 		break;
    863 	case 'c': case 'p':
    864 		if (tolower(what) == 'c')
    865 			x = cursor.col + 1, y = cursor.row + 1;
    866 		line = (alt ? 0 : scrolled) + y - 1;
    867 		for (i = nplaces - 1; i >= 0; i--)
    868 			if (places[i].alt == alt && line >= places[i].line && line < places[i].line + places[i].rows
    869 			&& x - 1 >= places[i].col && x - 1 < places[i].col + places[i].cols)
    870 				delplace(i);
    871 		break;
    872 	default:
    873 		/* everything on the screen */
    874 		for (i = nplaces - 1; i >= 0; i--)
    875 			if (places[i].alt == alt && places[i].line + places[i].rows > (alt ? 0 : scrolled))
    876 				delplace(i);
    877 		if (all)
    878 			for (i = nimages - 1; i >= 0; i--) {
    879 				int j, used = 0;
    880 
    881 				for (j = 0; j < nplaces; j++)
    882 					used |= places[j].img == images[i];
    883 				if (!used)
    884 					freeimage(images[i]);
    885 			}
    886 		break;
    887 	}
    888 	dirty = 1;
    889 }
    890 
    891 static int
    892 intemp(const char *path)
    893 {
    894 	const char *dirs[] = { "/tmp/", "/dev/shm/", "/var/tmp/", getenv("TMPDIR") };
    895 	struct stat st;
    896 	char real[PATH_MAX], dir[PATH_MAX];
    897 	unsigned int i;
    898 	size_t n;
    899 
    900 	if (lstat(path, &st) < 0 || !S_ISREG(st.st_mode) || !realpath(path, real) || strstr(real, "/../"))
    901 		return 0;
    902 	for (i = 0; i < LENGTH(dirs); i++) {
    903 		if (!dirs[i] || !*dirs[i])
    904 			continue;
    905 		snprintf(dir, sizeof dir, "%s%s", dirs[i], dirs[i][strlen(dirs[i]) - 1] == '/' ? "" : "/");
    906 		n = strlen(dir);
    907 		if (!strncmp(real, dir, n) && !strchr(real + n, '/'))
    908 			return 1;
    909 	}
    910 	return 0;
    911 }
    912 
    913 /* ESC _ G key=value,... ; base64 ESC \ */
    914 static void
    915 graphics(char *s, size_t n)
    916 {
    917 	static struct { unsigned int id, pid; int fmt, w, h, comp, quiet, c, r, nomove, z, x, y, sw, sh; char act, medium; } k;
    918 	static int more;
    919 	static unsigned char *data;
    920 	static size_t datalen;
    921 	char *payload, *kv, *e, *v;
    922 	unsigned char *raw;
    923 	size_t plen, rawlen;
    924 	uLongf zlen;
    925 	Image *im;
    926 	uint32_t *px;
    927 	char path[PATH_MAX];
    928 	FILE *f;
    929 	struct stat st;
    930 	int len, i;
    931 
    932 	payload = memchr(s, ';', n);
    933 	plen = payload ? n - (payload - s) - 1 : 0;
    934 	if (payload)
    935 		*payload++ = '\0';
    936 	else
    937 		s[n] = '\0';
    938 	if (!more) {
    939 		memset(&k, 0, sizeof k);
    940 		k.act = 't', k.medium = 'd', k.fmt = 32;
    941 		free(data);
    942 		data = NULL, datalen = 0;
    943 	}
    944 	more = 0;
    945 	for (kv = s + 1; kv && *kv; kv = e) {
    946 		if ((e = strchr(kv, ',')))
    947 			*e++ = '\0';
    948 		if (!(v = strchr(kv, '=')))
    949 			continue;
    950 		*v++ = '\0';
    951 		switch (*kv) {
    952 		case 'a': k.act = *v; break;
    953 		case 't': k.medium = *v; break;
    954 		case 'f': k.fmt = atoi(v); break;
    955 		case 'o': k.comp = *v; break;
    956 		case 'i': k.id = strtoul(v, NULL, 10); break;
    957 		case 'p': k.pid = strtoul(v, NULL, 10); break;
    958 		case 's': k.w = atoi(v); break;
    959 		case 'v': k.h = atoi(v); break;
    960 		case 'c': k.c = atoi(v); break;
    961 		case 'r': k.r = atoi(v); break;
    962 		case 'C': k.nomove = atoi(v); break;
    963 		case 'z': k.z = atoi(v); break;
    964 		case 'x': k.x = atoi(v); break;
    965 		case 'y': k.y = atoi(v); break;
    966 		case 'w': k.sw = atoi(v); break;
    967 		case 'h': k.sh = atoi(v); break;
    968 		case 'q': k.quiet = atoi(v); break;
    969 		case 'm': more = atoi(v); break;
    970 		case 'd': k.medium = *v; break;	/* for a=d, what to delete */
    971 		}
    972 	}
    973 	if (k.act == 'd') {
    974 		more = 0;
    975 		delete(k.medium == 'd' ? 'a' : k.medium, k.id, k.x, k.y);
    976 		return;
    977 	}
    978 	if (k.act == 'p') {
    979 		if (!(im = findimage(k.id)))
    980 			reply(k.id, k.pid, k.quiet, "ENOENT:no such image");
    981 		else {
    982 			place(im, k.pid, k.c, k.r, k.nomove, k.z, k.x, k.y, k.sw, k.sh);
    983 			reply(k.id, k.pid, k.quiet, "OK");
    984 		}
    985 		return;
    986 	}
    987 	/* the picture's bytes, maybe in pieces */
    988 	if (plen && datalen + plen < MAXAPC) {
    989 		data = realloc(data, datalen + plen);
    990 		memcpy(data + datalen, payload, plen);
    991 		datalen += plen;
    992 	}
    993 	if (more)
    994 		return;
    995 	raw = malloc(datalen * 3 / 4 + 4);
    996 	rawlen = raw ? unbase64((char *)data, datalen, raw) : 0;
    997 	free(data);
    998 	data = NULL, datalen = 0;
    999 	if (k.medium == 'f' || k.medium == 't') {
   1000 		/* a file's name instead of the picture */
   1001 		len = MIN(rawlen, sizeof path - 1);
   1002 		memcpy(path, raw, len);
   1003 		path[len] = '\0';
   1004 		free(raw);
   1005 		raw = NULL, rawlen = 0;
   1006 		if (stat(path, &st) == 0 && S_ISREG(st.st_mode) && st.st_size < MAXAPC && (f = fopen(path, "rb"))) {
   1007 			raw = malloc(st.st_size + 1);
   1008 			rawlen = raw ? fread(raw, 1, st.st_size, f) : 0;
   1009 			fclose(f);
   1010 		}
   1011 		/* t means "delete it after": only ever in a temporary folder, or anything a program prints
   1012 		   could delete your files */
   1013 		if (k.medium == 't' && strstr(path, "tty-graphics-protocol") && intemp(path))
   1014 			unlink(path);
   1015 	} else if (k.medium != 'd') {
   1016 		free(raw);
   1017 		reply(k.id, k.pid, k.quiet, "EINVAL:only direct and file");
   1018 		return;
   1019 	}
   1020 	if (k.comp == 'z' && raw && k.fmt != 100) {
   1021 		zlen = (uLongf)k.w * k.h * (k.fmt == 24 ? 3 : 4);
   1022 		unsigned char *z = malloc(zlen);
   1023 
   1024 		if (!z || uncompress(z, &zlen, raw, rawlen) != Z_OK) {
   1025 			free(z);
   1026 			free(raw);
   1027 			reply(k.id, k.pid, k.quiet, "EINVAL:bad zlib data");
   1028 			return;
   1029 		}
   1030 		free(raw);
   1031 		raw = z, rawlen = zlen;
   1032 	}
   1033 	if (k.act == 'q') {
   1034 		/* is anyone there: yes */
   1035 		free(raw);
   1036 		reply(k.id, k.pid, k.quiet, "OK");
   1037 		return;
   1038 	}
   1039 	px = raw ? topixels(k.fmt, raw, rawlen, &k.w, &k.h) : NULL;
   1040 	free(raw);
   1041 	if (!px) {
   1042 		reply(k.id, k.pid, k.quiet, "EBADPNG:can't read the picture");
   1043 		return;
   1044 	}
   1045 	if ((im = findimage(k.id)))
   1046 		freeimage(im);
   1047 	if (nimages == MAXIMAGES) {
   1048 		/* the oldest one that isn't on the screen goes */
   1049 		for (i = 0; i < nimages; i++) {
   1050 			int j, used = 0;
   1051 
   1052 			for (j = 0; j < nplaces; j++)
   1053 				used |= places[j].img == images[i];
   1054 			if (!used)
   1055 				break;
   1056 		}
   1057 		freeimage(images[i < nimages ? i : 0]);
   1058 	}
   1059 	im = calloc(1, sizeof *im);
   1060 	im->id = k.id, im->w = k.w, im->h = k.h, im->argb = px;
   1061 	images[nimages++] = im;
   1062 	if (k.act == 'T')
   1063 		place(im, k.pid, k.c, k.r, k.nomove, k.z, k.x, k.y, k.sw, k.sh);
   1064 	reply(k.id, k.pid, k.quiet, "OK");
   1065 }
   1066 
   1067 static int
   1068 onapc(VTermStringFragment frag, void *user)
   1069 {
   1070 	if (frag.initial)
   1071 		apclen = 0;
   1072 	if (apclen + frag.len + 1 > apcsize && apclen + frag.len < MAXAPC) {
   1073 		apcsize = (apclen + frag.len + 1) * 2;
   1074 		apc = realloc(apc, apcsize);
   1075 	}
   1076 	if (apclen + frag.len + 1 <= apcsize) {
   1077 		memcpy(apc + apclen, frag.str, frag.len);
   1078 		apclen += frag.len;
   1079 	}
   1080 	if (frag.final && apclen && apc[0] == 'G') {
   1081 		apc[apclen] = '\0';
   1082 		graphics(apc, apclen);
   1083 	}
   1084 	return 1;
   1085 }
   1086 
   1087 /* what libvterm doesn't answer: the window's size in pixels, and who we are */
   1088 static int
   1089 oncsi(const char *leader, const long args[], int argc, const char *intermed, char cmd, void *user)
   1090 {
   1091 	char s[64];
   1092 	int n = 0;
   1093 
   1094 	if (cmd == 't' && !leader && argc > 0) {
   1095 		if (CSI_ARG(args[0]) == 14)
   1096 			n = snprintf(s, sizeof s, "\033[4;%d;%dt", rows * ch, cols * cw);
   1097 		else if (CSI_ARG(args[0]) == 16)
   1098 			n = snprintf(s, sizeof s, "\033[6;%d;%dt", ch, cw);
   1099 		else if (CSI_ARG(args[0]) == 18)
   1100 			n = snprintf(s, sizeof s, "\033[8;%d;%dt", rows, cols);
   1101 	} else if (cmd == 'q' && leader && leader[0] == '>')
   1102 		n = snprintf(s, sizeof s, "\033P>|tyrmel " VERSION "\033\\");
   1103 	if (n)
   1104 		writepty(s, n);
   1105 	return n > 0;
   1106 }
   1107 
   1108 static VTermStateFallbacks fallbacks = { .csi = oncsi, .apc = onapc };
   1109 
   1110 /* ---- libvterm tells us what changed ---- */
   1111 
   1112 static int
   1113 ondamage(VTermRect r, void *user)
   1114 {
   1115 	dirty = 1;
   1116 	return 1;
   1117 }
   1118 
   1119 static int
   1120 onmovecursor(VTermPos pos, VTermPos old, int visible, void *user)
   1121 {
   1122 	cursor = pos;
   1123 	dirty = 1;
   1124 	return 1;
   1125 }
   1126 
   1127 static int
   1128 onprop(VTermProp prop, VTermValue *val, void *user)
   1129 {
   1130 	static char title[1024];
   1131 	static size_t tlen;
   1132 	XTextProperty tp;
   1133 	char *t = title;
   1134 	int i;
   1135 
   1136 	switch (prop) {
   1137 	case VTERM_PROP_TITLE:
   1138 		if (val->string.initial)
   1139 			tlen = 0;
   1140 		if (tlen + val->string.len < sizeof title) {
   1141 			memcpy(title + tlen, val->string.str, val->string.len);
   1142 			tlen += val->string.len;
   1143 		}
   1144 		title[tlen] = '\0';
   1145 		if (val->string.final && !wtitle) {
   1146 			Xutf8TextListToTextProperty(dpy, &t, 1, XUTF8StringStyle, &tp);
   1147 			XSetWMName(dpy, win, &tp);
   1148 			XFree(tp.value);
   1149 			XChangeProperty(dpy, win, netwmname, xutf8, 8, PropModeReplace, (unsigned char *)title, tlen);
   1150 		}
   1151 		break;
   1152 	case VTERM_PROP_ALTSCREEN:
   1153 		alt = val->boolean;
   1154 		/* pictures on the screen a program was using go with it */
   1155 		for (i = nplaces - 1; i >= 0; i--)
   1156 			if (places[i].alt)
   1157 				delplace(i);
   1158 		view = 0;
   1159 		dirty = 1;
   1160 		break;
   1161 	case VTERM_PROP_CURSORVISIBLE:
   1162 		cursorvisible = val->boolean;
   1163 		dirty = 1;
   1164 		break;
   1165 	case VTERM_PROP_CURSORSHAPE:
   1166 		cursorshape = val->number;
   1167 		dirty = 1;
   1168 		break;
   1169 	case VTERM_PROP_MOUSE:
   1170 		mousemode = val->number;
   1171 		break;
   1172 	default:
   1173 		break;
   1174 	}
   1175 	return 1;
   1176 }
   1177 
   1178 static int
   1179 onbell(void *user)
   1180 {
   1181 	XWMHints *h = XGetWMHints(dpy, win);
   1182 
   1183 	if (!focused && h) {
   1184 		h->flags |= XUrgencyHint;
   1185 		XSetWMHints(dpy, win, h);
   1186 	}
   1187 	if (h)
   1188 		XFree(h);
   1189 	return 1;
   1190 }
   1191 
   1192 static VTermScreenCallbacks screencb = {
   1193 	.damage = ondamage,
   1194 	.movecursor = onmovecursor,
   1195 	.settermprop = onprop,
   1196 	.bell = onbell,
   1197 	.sb_pushline = sbpush,
   1198 	.sb_popline = sbpop,
   1199 	.sb_clear = sbclear,
   1200 };
   1201 
   1202 static void
   1203 ontermoutput(const char *s, size_t n, void *user)
   1204 {
   1205 	writepty(s, n);
   1206 }
   1207 
   1208 /* ---- drawing ---- */
   1209 
   1210 static int
   1211 selected(long r, int c)
   1212 {
   1213 	long a0 = sel.r0, a1 = sel.r1;
   1214 	int b0 = sel.c0, b1 = sel.c1;
   1215 
   1216 	if (!sel.on)
   1217 		return 0;
   1218 	if (a0 > a1 || (a0 == a1 && b0 > b1)) {
   1219 		long t = a0; a0 = a1; a1 = t;
   1220 		int u = b0; b0 = b1; b1 = u;
   1221 	}
   1222 	if (r < a0 || r > a1)
   1223 		return 0;
   1224 	if (r == a0 && c < b0)
   1225 		return 0;
   1226 	if (r == a1 && c > b1)
   1227 		return 0;
   1228 	return 1;
   1229 }
   1230 
   1231 static void
   1232 drawimages(int under)
   1233 {
   1234 	long top = (alt ? 0 : scrolled) - view;
   1235 	int i, x, y;
   1236 
   1237 	for (i = 0; i < nplaces; i++) {
   1238 		if (places[i].alt != alt || (places[i].z < 0) != under)
   1239 			continue;
   1240 		y = (places[i].line - top) * ch;
   1241 		x = places[i].col * cw;
   1242 		if (y >= rows * ch || y + places[i].rows * ch <= 0)
   1243 			continue;
   1244 		makepic(&places[i]);
   1245 		if (places[i].pic)
   1246 			XRenderComposite(dpy, PictOpOver, places[i].pic, None, bufpic, 0, 0, 0, 0, x, y,
   1247 			                 places[i].cols * cw, places[i].rows * ch);
   1248 	}
   1249 }
   1250 
   1251 /* letters of one colour and font next to each other go in one call */
   1252 static void
   1253 flushrun(FcChar8 *run, int *len, XftFont *f, XftColor *c, int x, int y)
   1254 {
   1255 	if (*len)
   1256 		XftDrawStringUtf8(draw, c, f, x, y, run, *len);
   1257 	*len = 0;
   1258 }
   1259 
   1260 static void
   1261 redraw(void)
   1262 {
   1263 	static Cell *grid;
   1264 	static int gridsize;
   1265 	static FcChar8 run[4096];
   1266 	int runlen = 0, runx = 0;
   1267 	XftFont *runf = NULL;
   1268 	uint8_t runrgb[3] = { 0 };
   1269 	const uint8_t *rgb;
   1270 	Cell *row;
   1271 	XftColor fg, bg, cc;
   1272 	uint8_t crgb[3], dfg[3], dbg[3];
   1273 	XftFont *f;
   1274 	FcChar8 u[8];
   1275 	Cell *c;
   1276 	int r, x, len, isfg, rev;
   1277 	long vr;
   1278 
   1279 	if (gridsize < rows * cols) {
   1280 		grid = realloc(grid, rows * cols * sizeof *grid);
   1281 		gridsize = rows * cols;
   1282 	}
   1283 	for (r = 0; r < rows; r++)
   1284 		viewrow(r, grid + r * cols);
   1285 	if (!parsecolour(fgname, dfg))
   1286 		parsecolour("grey", dfg);
   1287 	if (!parsecolour(bgname, dbg))
   1288 		parsecolour("black", dbg);
   1289 	xcolour(dbg, &bg);
   1290 	XftDrawRect(draw, &bg, 0, 0, ww, wh);
   1291 	/* backgrounds first, then pictures under the text, the text, and pictures over it */
   1292 	for (r = 0; r < rows; r++) {
   1293 		row = grid + r * cols;
   1294 		vr = (long)sbn - view + r;
   1295 		for (x = 0; x < cols; x++) {
   1296 			c = &row[x];
   1297 			rev = !!(c->flags & FReverse) ^ selected(vr, x);
   1298 			if (!rev && (c->flags & FDefBg))
   1299 				continue;
   1300 			xcolour(rev ? (c->flags & FDefFg ? dfg : c->fg) : c->bg, &bg);
   1301 			XftDrawRect(draw, &bg, x * cw, r * ch, cw * MAX(c->width, 1), ch);
   1302 		}
   1303 	}
   1304 	drawimages(1);
   1305 	for (r = 0; r < rows; r++) {
   1306 		row = grid + r * cols;
   1307 		vr = (long)sbn - view + r;
   1308 		for (x = 0; x < cols; x++) {
   1309 			c = &row[x];
   1310 			if (!c->ch || c->ch == ' ' || c->ch == (uint32_t)-1) {
   1311 				flushrun(run, &runlen, runf, &fg, runx, r * ch + ascent);
   1312 				continue;
   1313 			}
   1314 			rev = !!(c->flags & FReverse) ^ selected(vr, x);
   1315 			isfg = !(c->flags & FDefFg);
   1316 			rgb = rev ? (c->flags & FDefBg ? dbg : c->bg) : isfg ? c->fg : dfg;
   1317 			f = fontfor(c->ch);
   1318 			/* a new run when the colour or font changes, or after a wide letter */
   1319 			if (runlen && (f != runf || memcmp(rgb, runrgb, 3) || runlen > (int)sizeof run - 8))
   1320 				flushrun(run, &runlen, runf, &fg, runx, r * ch + ascent);
   1321 			if (!runlen) {
   1322 				xcolour(rgb, &fg);
   1323 				memcpy(runrgb, rgb, 3);
   1324 				runf = f;
   1325 				runx = x * cw;
   1326 			}
   1327 			len = FcUcs4ToUtf8(c->ch, u);
   1328 			memcpy(run + runlen, u, len);
   1329 			runlen += len;
   1330 			if (f != fonts.font || c->width != 1 || !samewidth)
   1331 				flushrun(run, &runlen, runf, &fg, runx, r * ch + ascent);
   1332 			if (c->flags & FUnder)
   1333 				XftDrawRect(draw, &fg, x * cw, r * ch + ascent + 1, cw * MAX(c->width, 1), 1);
   1334 			if (c->flags & FStrike)
   1335 				XftDrawRect(draw, &fg, x * cw, r * ch + ch / 2, cw * MAX(c->width, 1), 1);
   1336 		}
   1337 		flushrun(run, &runlen, runf, &fg, runx, r * ch + ascent);
   1338 	}
   1339 	drawimages(0);
   1340 	/* the cursor */
   1341 	if (cursorvisible && !view) {
   1342 		if (!parsecolour(cursorname, crgb))
   1343 			parsecolour("grey", crgb);
   1344 		xcolour(crgb, &cc);
   1345 		x = cursor.col * cw, r = cursor.row * ch;
   1346 		if (!focused) {
   1347 			XftDrawRect(draw, &cc, x, r, cw, 1);
   1348 			XftDrawRect(draw, &cc, x, r + ch - 1, cw, 1);
   1349 			XftDrawRect(draw, &cc, x, r, 1, ch);
   1350 			XftDrawRect(draw, &cc, x + cw - 1, r, 1, ch);
   1351 		} else if (cursorshape == VTERM_PROP_CURSORSHAPE_UNDERLINE)
   1352 			XftDrawRect(draw, &cc, x, r + ch - 2, cw, 2);
   1353 		else if (cursorshape == VTERM_PROP_CURSORSHAPE_BAR_LEFT)
   1354 			XftDrawRect(draw, &cc, x, r, 2, ch);
   1355 		else {
   1356 			/* the letter under it, in the background colour */
   1357 			XftDrawRect(draw, &cc, x, r, cw, ch);
   1358 			c = &grid[cursor.row * cols + cursor.col];
   1359 			if (c->ch && c->ch != ' ' && c->ch != (uint32_t)-1) {
   1360 				xcolour(dbg, &bg);
   1361 				len = FcUcs4ToUtf8(c->ch, u);
   1362 				XftDrawStringUtf8(draw, &bg, fontfor(c->ch), x, r + ascent, u, len);
   1363 			}
   1364 		}
   1365 	}
   1366 	/* where you are in the scrollback */
   1367 	if (view) {
   1368 		char s[32];
   1369 
   1370 		snprintf(s, sizeof s, " %d/%d ", view, sbn);
   1371 		xcolour(dfg, &fg);
   1372 		len = strlen(s);
   1373 		XftDrawRect(draw, &fg, ww - len * cw, 0, len * cw, ch);
   1374 		xcolour(dbg, &bg);
   1375 		XftDrawStringUtf8(draw, &bg, fonts.font, ww - len * cw, ascent, (FcChar8 *)s, len);
   1376 	}
   1377 	XCopyArea(dpy, buf, win, gc, 0, 0, ww, wh, 0, 0);
   1378 	dirty = 0;
   1379 }
   1380 
   1381 /* ---- the window ---- */
   1382 
   1383 static void
   1384 setsizehints(void)
   1385 {
   1386 	XSizeHints *h = XAllocSizeHints();
   1387 
   1388 	h->flags = PResizeInc | PBaseSize | PMinSize;
   1389 	h->width_inc = cw, h->height_inc = ch;
   1390 	h->base_width = h->base_height = 0;
   1391 	h->min_width = cw * 2, h->min_height = ch;
   1392 	XSetWMNormalHints(dpy, win, h);
   1393 	XFree(h);
   1394 }
   1395 
   1396 static void
   1397 resize(int w, int h)
   1398 {
   1399 	struct winsize ws;
   1400 	int c = MAX(w / cw, 1), r = MAX(h / ch, 1);
   1401 
   1402 	if (w != ww || h != wh || !buf) {
   1403 		ww = w, wh = h;
   1404 		if (draw)
   1405 			XftDrawDestroy(draw);
   1406 		if (bufpic)
   1407 			XRenderFreePicture(dpy, bufpic);
   1408 		if (buf)
   1409 			XFreePixmap(dpy, buf);
   1410 		buf = XCreatePixmap(dpy, win, ww, wh, depth);
   1411 		draw = XftDrawCreate(dpy, buf, vis, cmap);
   1412 		bufpic = XRenderCreatePicture(dpy, buf, XRenderFindVisualFormat(dpy, vis), 0, NULL);
   1413 	}
   1414 	if (c != cols || r != rows) {
   1415 		cols = c, rows = r;
   1416 		vterm_set_size(vt, rows, cols);
   1417 		vterm_screen_flush_damage(vs);
   1418 	}
   1419 	ws.ws_col = cols, ws.ws_row = rows;
   1420 	ws.ws_xpixel = cols * cw, ws.ws_ypixel = rows * ch;
   1421 	if (ptyfd >= 0)
   1422 		ioctl(ptyfd, TIOCSWINSZ, &ws);
   1423 	dirty = 1;
   1424 }
   1425 
   1426 static void
   1427 zoom(int size)
   1428 {
   1429 	int i;
   1430 
   1431 	if (size < 6 || size > 96)
   1432 		return;
   1433 	fontsize = size;
   1434 	loadfonts(size);
   1435 	for (i = 0; i < nplaces; i++)
   1436 		places[i].pw = 0;
   1437 	setsizehints();
   1438 	resize(ww, wh);
   1439 }
   1440 
   1441 /* ---- copy and paste ---- */
   1442 
   1443 static char *
   1444 gettext(long r0, int c0, long r1, int c1)
   1445 {
   1446 	static Cell *row;
   1447 	static int rowsize;
   1448 	size_t n = 0, size = 256;
   1449 	char *s = malloc(size);
   1450 	Line *l;
   1451 	long r;
   1452 	int c, end, last, m;
   1453 
   1454 	if (rowsize < cols) {
   1455 		row = realloc(row, cols * sizeof *row);
   1456 		rowsize = cols;
   1457 	}
   1458 	for (r = r0; r <= r1; r++) {
   1459 		if (r < 0 || r >= sbn + rows)
   1460 			continue;
   1461 		if (r < sbn) {
   1462 			l = sbline(r);
   1463 			end = l->cols;
   1464 			for (c = 0; c < end && c < cols; c++)
   1465 				row[c] = l->cells[c];
   1466 			end = MIN(end, cols);
   1467 		} else {
   1468 			int sv = view;
   1469 
   1470 			view = 0;
   1471 			viewrow(r - sbn, row);
   1472 			view = sv;
   1473 			end = cols;
   1474 		}
   1475 		/* no spaces at the end of lines */
   1476 		for (last = end; last > 0 && (!row[last - 1].ch || row[last - 1].ch == ' '); last--);
   1477 		for (c = r == r0 ? c0 : 0; c < last && (r != r1 || c <= c1); c++) {
   1478 			if (n + 8 >= size)
   1479 				s = realloc(s, size *= 2);
   1480 			if (row[c].width == 0 && c > 0 && row[c - 1].width == 2)
   1481 				continue;
   1482 			m = FcUcs4ToUtf8(row[c].ch && row[c].ch != (uint32_t)-1 ? row[c].ch : ' ', (FcChar8 *)s + n);
   1483 			n += m;
   1484 		}
   1485 		if (r != r1) {
   1486 			if (n + 2 >= size)
   1487 				s = realloc(s, size *= 2);
   1488 			s[n++] = '\n';
   1489 		}
   1490 	}
   1491 	s[n] = '\0';
   1492 	return s;
   1493 }
   1494 
   1495 static void
   1496 own(Atom which)
   1497 {
   1498 	long r0 = sel.r0, r1 = sel.r1;
   1499 	int c0 = sel.c0, c1 = sel.c1;
   1500 
   1501 	if (r0 > r1 || (r0 == r1 && c0 > c1)) {
   1502 		long t = r0; r0 = r1; r1 = t;
   1503 		int u = c0; c0 = c1; c1 = u;
   1504 	}
   1505 	free(seltext);
   1506 	seltext = gettext(r0, c0, r1, c1);
   1507 	XSetSelectionOwner(dpy, which, win, CurrentTime);
   1508 }
   1509 
   1510 static void
   1511 selectionrequest(XSelectionRequestEvent *e)
   1512 {
   1513 	XSelectionEvent ev = { SelectionNotify };
   1514 	Atom targets[] = { xtargets, xutf8, XA_STRING };
   1515 
   1516 	ev.requestor = e->requestor;
   1517 	ev.selection = e->selection;
   1518 	ev.target = e->target;
   1519 	ev.time = e->time;
   1520 	ev.property = e->property ? e->property : e->target;
   1521 	if (e->target == xtargets)
   1522 		XChangeProperty(dpy, e->requestor, ev.property, XA_ATOM, 32, PropModeReplace,
   1523 		                (unsigned char *)targets, LENGTH(targets));
   1524 	else if ((e->target == xutf8 || e->target == XA_STRING) && seltext)
   1525 		XChangeProperty(dpy, e->requestor, ev.property, e->target, 8, PropModeReplace,
   1526 		                (unsigned char *)seltext, strlen(seltext));
   1527 	else
   1528 		ev.property = None;
   1529 	XSendEvent(dpy, e->requestor, False, 0, (XEvent *)&ev);
   1530 }
   1531 
   1532 static void
   1533 paste(Atom which)
   1534 {
   1535 	XConvertSelection(dpy, which, xutf8, xprop, win, CurrentTime);
   1536 }
   1537 
   1538 static void
   1539 selectionnotify(XSelectionEvent *e)
   1540 {
   1541 	unsigned char *data;
   1542 	unsigned long n, after;
   1543 	Atom type;
   1544 	int fmt;
   1545 	unsigned long i;
   1546 
   1547 	if (e->property == None)
   1548 		return;
   1549 	if (XGetWindowProperty(dpy, win, e->property, 0, 1 << 20, True, AnyPropertyType, &type, &fmt,
   1550 	    &n, &after, &data) != Success)
   1551 		return;
   1552 	/* new lines are enter keys. other control characters go, like xterm does it: otherwise pasted
   1553 	   text could end the paste early and the rest would run as if you'd typed it */
   1554 	{
   1555 		unsigned long j = 0;
   1556 
   1557 		for (i = 0; i < n; i++) {
   1558 			if (data[i] == '\n')
   1559 				data[i] = '\r';
   1560 			if (data[i] < 0x20 && data[i] != '\r' && data[i] != '\t')
   1561 				continue;
   1562 			if (data[i] == 0x7f)
   1563 				continue;
   1564 			data[j++] = data[i];
   1565 		}
   1566 		n = j;
   1567 	}
   1568 	vterm_keyboard_start_paste(vt);
   1569 	writepty((char *)data, n);
   1570 	vterm_keyboard_end_paste(vt);
   1571 	XFree(data);
   1572 	view = 0;
   1573 	dirty = 1;
   1574 }
   1575 
   1576 /* ctrl+click: the address under the mouse, opened */
   1577 static void
   1578 openurl(long r, int c)
   1579 {
   1580 	static const char *starts[] = { "https://", "http://", "file://", "ftp://" };
   1581 	char *line, *p, *q, *url = NULL, cmd[4200];
   1582 	unsigned int i;
   1583 	int pos = 0, at;
   1584 
   1585 	line = gettext(r, 0, r, cols);
   1586 	/* the byte where the click was */
   1587 	for (p = line, at = 0; *p && at < c; p++)
   1588 		if ((*p & 0xc0) != 0x80)
   1589 			at++;
   1590 	pos = p - line;
   1591 	for (i = 0; i < LENGTH(starts); i++)
   1592 		for (p = line; (p = strstr(p, starts[i])); p++) {
   1593 			for (q = p; *q && !isspace((unsigned char)*q) && !strchr("<>\"'`", *q); q++);
   1594 			if (pos >= p - line && pos < q - line) {
   1595 				*q = '\0';
   1596 				url = p;
   1597 				break;
   1598 			}
   1599 		}
   1600 	if (url && !strchr(url, '\'')) {
   1601 		snprintf(cmd, sizeof cmd, "xdg-open '%s' >/dev/null 2>&1 &", url);
   1602 		if (system(cmd) < 0)
   1603 			fprintf(stderr, "tyrmel: can't open %s\n", url);
   1604 	}
   1605 	free(line);
   1606 }
   1607 
   1608 static int
   1609 isword(uint32_t c)
   1610 {
   1611 	return c && c != ' ' && !strchr("()[]{}<>'\"`|;,", c < 128 ? (int)c : 'a');
   1612 }
   1613 
   1614 /* ---- keys and the mouse ---- */
   1615 
   1616 static VTermModifier
   1617 mods(unsigned int state)
   1618 {
   1619 	return (state & ShiftMask ? VTERM_MOD_SHIFT : 0) | (state & ControlMask ? VTERM_MOD_CTRL : 0) |
   1620 	       (state & Mod1Mask ? VTERM_MOD_ALT : 0);
   1621 }
   1622 
   1623 static void
   1624 scrollview(int n)
   1625 {
   1626 	view = MIN(MAX(view + n, 0), sbn);
   1627 	dirty = 1;
   1628 }
   1629 
   1630 static void
   1631 keypress(XKeyEvent *e)
   1632 {
   1633 	static const struct { KeySym sym; VTermKey key; } keys[] = {
   1634 		{ XK_Return, VTERM_KEY_ENTER }, { XK_KP_Enter, VTERM_KEY_KP_ENTER }, { XK_Tab, VTERM_KEY_TAB },
   1635 		{ XK_ISO_Left_Tab, VTERM_KEY_TAB }, { XK_BackSpace, VTERM_KEY_BACKSPACE }, { XK_Escape, VTERM_KEY_ESCAPE },
   1636 		{ XK_Up, VTERM_KEY_UP }, { XK_Down, VTERM_KEY_DOWN }, { XK_Left, VTERM_KEY_LEFT }, { XK_Right, VTERM_KEY_RIGHT },
   1637 		{ XK_Insert, VTERM_KEY_INS }, { XK_Delete, VTERM_KEY_DEL }, { XK_Home, VTERM_KEY_HOME }, { XK_End, VTERM_KEY_END },
   1638 		{ XK_Page_Up, VTERM_KEY_PAGEUP }, { XK_Page_Down, VTERM_KEY_PAGEDOWN },
   1639 		{ XK_KP_Up, VTERM_KEY_UP }, { XK_KP_Down, VTERM_KEY_DOWN }, { XK_KP_Left, VTERM_KEY_LEFT },
   1640 		{ XK_KP_Right, VTERM_KEY_RIGHT }, { XK_KP_Home, VTERM_KEY_HOME }, { XK_KP_End, VTERM_KEY_END },
   1641 		{ XK_KP_Page_Up, VTERM_KEY_PAGEUP }, { XK_KP_Page_Down, VTERM_KEY_PAGEDOWN },
   1642 		{ XK_KP_Insert, VTERM_KEY_INS }, { XK_KP_Delete, VTERM_KEY_DEL },
   1643 	};
   1644 	char text[64];
   1645 	KeySym sym;
   1646 	Status st;
   1647 	VTermModifier m = mods(e->state);
   1648 	unsigned int i;
   1649 	int n;
   1650 	uint32_t c;
   1651 	const char *p;
   1652 
   1653 	n = xic ? Xutf8LookupString(xic, e, text, sizeof text - 1, &sym, &st) : XLookupString(e, text, sizeof text - 1, &sym, NULL);
   1654 	text[MAX(n, 0)] = '\0';
   1655 	/* ours: copy, paste, scrolling, the font size */
   1656 	if ((e->state & ControlMask) && (e->state & ShiftMask)) {
   1657 		switch (XkbKeycodeToKeysym(dpy, e->keycode, 0, 0)) {
   1658 		case XK_c: if (sel.on) own(xclipboard); return;
   1659 		case XK_v: paste(xclipboard); return;
   1660 		case XK_equal: case XK_plus: zoom(fontsize + 2); return;
   1661 		case XK_minus: zoom(fontsize - 2); return;
   1662 		case XK_0: zoom(basesize); return;
   1663 		}
   1664 	}
   1665 	if ((e->state & ShiftMask) && !(e->state & ControlMask)) {
   1666 		switch (sym) {
   1667 		case XK_Page_Up: case XK_KP_Page_Up: scrollview(rows / 2); return;
   1668 		case XK_Page_Down: case XK_KP_Page_Down: scrollview(-rows / 2); return;
   1669 		case XK_Insert: case XK_KP_Insert: paste(XA_PRIMARY); return;
   1670 		}
   1671 	}
   1672 	if (sym == XK_Shift_L || sym == XK_Shift_R || sym == XK_Control_L || sym == XK_Control_R ||
   1673 	    sym == XK_Alt_L || sym == XK_Alt_R || sym == XK_Super_L || sym == XK_Super_R || sym == XK_Caps_Lock)
   1674 		return;
   1675 	view = 0;
   1676 	dirty = 1;
   1677 	for (i = 0; i < LENGTH(keys); i++)
   1678 		if (keys[i].sym == sym) {
   1679 			vterm_keyboard_key(vt, keys[i].key, m);
   1680 			return;
   1681 		}
   1682 	if (sym >= XK_F1 && sym <= XK_F12) {
   1683 		vterm_keyboard_key(vt, VTERM_KEY_FUNCTION(sym - XK_F1 + 1), m);
   1684 		return;
   1685 	}
   1686 	if (e->state & ControlMask) {
   1687 		/* ctrl+letter: the letter itself, libvterm makes the control code */
   1688 		sym = XkbKeycodeToKeysym(dpy, e->keycode, 0, 0);
   1689 		c = sym < 0x100 ? sym : (sym & 0xff000000) == 0x01000000 ? sym & 0xffffff : 0;
   1690 		if (c) {
   1691 			vterm_keyboard_unichar(vt, c, m & ~VTERM_MOD_SHIFT);
   1692 			return;
   1693 		}
   1694 	}
   1695 	/* what the keyboard layout made, the shift already in it */
   1696 	for (p = text; *p;) {
   1697 		FcChar32 u;
   1698 		int l = FcUtf8ToUcs4((FcChar8 *)p, &u, strlen(p));
   1699 
   1700 		if (l <= 0)
   1701 			break;
   1702 		vterm_keyboard_unichar(vt, u, m & VTERM_MOD_ALT);
   1703 		p += l;
   1704 	}
   1705 }
   1706 
   1707 static void
   1708 cellat(int x, int y, long *r, int *c)
   1709 {
   1710 	*c = MIN(MAX(x / cw, 0), cols - 1);
   1711 	*r = (long)sbn - view + MIN(MAX(y / ch, 0), rows - 1);
   1712 }
   1713 
   1714 static void
   1715 buttonpress(XButtonEvent *e)
   1716 {
   1717 	long r;
   1718 	int c;
   1719 
   1720 	/* programs that want the mouse get it, unless shift is held */
   1721 	if (mousemode && !(e->state & ShiftMask)) {
   1722 		vterm_mouse_move(vt, MIN(e->y / ch, rows - 1), MIN(e->x / cw, cols - 1), mods(e->state));
   1723 		vterm_mouse_button(vt, e->button, 1, mods(e->state));
   1724 		return;
   1725 	}
   1726 	if (e->button == Button4) {
   1727 		if (alt) vterm_keyboard_key(vt, VTERM_KEY_UP, 0), vterm_keyboard_key(vt, VTERM_KEY_UP, 0), vterm_keyboard_key(vt, VTERM_KEY_UP, 0);
   1728 		else scrollview(3);
   1729 		return;
   1730 	}
   1731 	if (e->button == Button5) {
   1732 		if (alt) vterm_keyboard_key(vt, VTERM_KEY_DOWN, 0), vterm_keyboard_key(vt, VTERM_KEY_DOWN, 0), vterm_keyboard_key(vt, VTERM_KEY_DOWN, 0);
   1733 		else scrollview(-3);
   1734 		return;
   1735 	}
   1736 	if (e->button == Button2) {
   1737 		paste(XA_PRIMARY);
   1738 		return;
   1739 	}
   1740 	if (e->button != Button1)
   1741 		return;
   1742 	cellat(e->x, e->y, &r, &c);
   1743 	if (e->state & ControlMask) {
   1744 		openurl(r, c);
   1745 		return;
   1746 	}
   1747 	clicks = e->time - lastclick < 400 ? clicks + 1 : 1;
   1748 	lastclick = e->time;
   1749 	sel.r0 = sel.r1 = r;
   1750 	sel.c0 = sel.c1 = c;
   1751 	sel.on = 0;
   1752 	sel.going = 1;
   1753 	if (clicks >= 2) {
   1754 		/* two clicks a word, three the line */
   1755 		static Cell *row;
   1756 		static int rowsize;
   1757 		int a = c, b = c;
   1758 
   1759 		if (rowsize < cols) {
   1760 			row = realloc(row, cols * sizeof *row);
   1761 			rowsize = cols;
   1762 		}
   1763 		if (r >= sbn) {
   1764 			int sv = view;
   1765 
   1766 			view = 0;
   1767 			viewrow(r - sbn, row);
   1768 			view = sv;
   1769 		} else {
   1770 			Line *l = sbline(r);
   1771 			int i;
   1772 
   1773 			for (i = 0; i < cols; i++)
   1774 				row[i] = i < l->cols ? l->cells[i] : (Cell){ 0 };
   1775 		}
   1776 		if (clicks == 2) {
   1777 			while (a > 0 && isword(row[a - 1].ch))
   1778 				a--;
   1779 			while (b < cols - 1 && isword(row[b + 1].ch))
   1780 				b++;
   1781 		} else
   1782 			a = 0, b = cols - 1;
   1783 		sel.c0 = a, sel.c1 = b;
   1784 		sel.on = 1;
   1785 		own(XA_PRIMARY);
   1786 	}
   1787 	dirty = 1;
   1788 }
   1789 
   1790 static void
   1791 buttonrelease(XButtonEvent *e)
   1792 {
   1793 	if (mousemode && !(e->state & ShiftMask)) {
   1794 		vterm_mouse_move(vt, MIN(e->y / ch, rows - 1), MIN(e->x / cw, cols - 1), mods(e->state));
   1795 		vterm_mouse_button(vt, e->button, 0, mods(e->state));
   1796 		return;
   1797 	}
   1798 	if (e->button == Button1 && sel.going) {
   1799 		sel.going = 0;
   1800 		if (sel.on)
   1801 			own(XA_PRIMARY);
   1802 	}
   1803 }
   1804 
   1805 static void
   1806 motion(XMotionEvent *e)
   1807 {
   1808 	long r;
   1809 	int c;
   1810 
   1811 	if (mousemode && !(e->state & ShiftMask)) {
   1812 		vterm_mouse_move(vt, MIN(e->y / ch, rows - 1), MIN(e->x / cw, cols - 1), mods(e->state));
   1813 		return;
   1814 	}
   1815 	if (!sel.going || clicks > 1)
   1816 		return;
   1817 	cellat(e->x, e->y, &r, &c);
   1818 	/* dragging past the top or bottom scrolls */
   1819 	if (e->y < 0)
   1820 		scrollview(1);
   1821 	else if (e->y >= wh)
   1822 		scrollview(-1);
   1823 	if (r != sel.r1 || c != sel.c1) {
   1824 		sel.r1 = r, sel.c1 = c;
   1825 		sel.on = 1;
   1826 		dirty = 1;
   1827 	}
   1828 }
   1829 
   1830 /* ---- the program in it ---- */
   1831 
   1832 static void
   1833 spawn(void)
   1834 {
   1835 	struct winsize ws = { rows, cols, cols * cw, rows * ch };
   1836 	const char *sh;
   1837 	char wid[32];
   1838 
   1839 	if ((child = forkpty(&ptyfd, NULL, NULL, &ws)) < 0)
   1840 		die("can't make a pty");
   1841 	if (child == 0) {
   1842 		snprintf(wid, sizeof wid, "%lu", win);
   1843 		setenv("TERM", "xterm-256color", 1);
   1844 		setenv("COLORTERM", "truecolor", 1);
   1845 		setenv("TERM_PROGRAM", "tyrmel", 1);
   1846 		setenv("TERM_PROGRAM_VERSION", VERSION, 1);
   1847 		setenv("WINDOWID", wid, 1);
   1848 		unsetenv("COLUMNS");
   1849 		unsetenv("LINES");
   1850 		signal(SIGCHLD, SIG_DFL);
   1851 		signal(SIGPIPE, SIG_DFL);
   1852 		if (cmdargv) {
   1853 			execvp(cmdargv[0], cmdargv);
   1854 			fprintf(stderr, "tyrmel: can't run %s\n", cmdargv[0]);
   1855 			_exit(127);
   1856 		}
   1857 		if (*shellcmd) {
   1858 			execl("/bin/sh", "sh", "-c", shellcmd, (char *)NULL);
   1859 			_exit(127);
   1860 		}
   1861 		sh = getenv("SHELL");
   1862 		if (!sh || !*sh)
   1863 			sh = "/bin/sh";
   1864 		execl(sh, sh, (char *)NULL);
   1865 		_exit(127);
   1866 	}
   1867 	fcntl(ptyfd, F_SETFL, fcntl(ptyfd, F_GETFL) | O_NONBLOCK);
   1868 }
   1869 
   1870 /* feed what the program wrote, stopping after each picture to move the cursor past it */
   1871 static void
   1872 feed(const char *s, size_t n)
   1873 {
   1874 	const char *st, *q;
   1875 	size_t k;
   1876 	char mv[32];
   1877 
   1878 	while (n > 0) {
   1879 		st = memmem(s, n, "\033\\", 2);
   1880 		k = st ? (size_t)(st - s) + 2 : n;
   1881 		/* "who are you": libvterm would say libvterm, and programs take that for neovim */
   1882 		if ((q = memmem(s, k, "\033[>q", 4)) || (q = memmem(s, k, "\033[>0q", 5))) {
   1883 			vterm_input_write(vt, s, q - s);
   1884 			writepty("\033P>|tyrmel " VERSION "\033\\", strlen("\033P>|tyrmel " VERSION "\033\\"));
   1885 			k = (q - s) + (q[3] == 'q' ? 4 : 5);
   1886 			s += k, n -= k;
   1887 			continue;
   1888 		}
   1889 		vterm_input_write(vt, s, k);
   1890 		if (pendingrows || pendingcols) {
   1891 			while (pendingrows-- > 0)
   1892 				vterm_input_write(vt, "\n", 1);
   1893 			snprintf(mv, sizeof mv, "\033[%dC", pendingcols);
   1894 			vterm_input_write(vt, mv, strlen(mv));
   1895 			pendingrows = pendingcols = 0;
   1896 		}
   1897 		/* clearing the screen clears the pictures on it */
   1898 		if (memmem(s, k, "\033[2J", 4) || memmem(s, k, "\033[3J", 4))
   1899 			delete('a', 0, 0, 0);
   1900 		s += k, n -= k;
   1901 	}
   1902 	vterm_screen_flush_damage(vs);
   1903 }
   1904 
   1905 static int
   1906 readpty(void)
   1907 {
   1908 	static char b[1 << 18];
   1909 	ssize_t n;
   1910 	int got = 0;
   1911 	long start = ms();
   1912 
   1913 	/* read for a frame at most, so a flood of output doesn't stop the drawing */
   1914 	while ((n = read(ptyfd, b, sizeof b)) > 0) {
   1915 		feed(b, n);
   1916 		got++;
   1917 		if (ms() - start >= 16)
   1918 			break;
   1919 	}
   1920 	if (n == 0 || (n < 0 && errno != EAGAIN && errno != EINTR))
   1921 		return -1;
   1922 	return got;
   1923 }
   1924 
   1925 static void
   1926 checkconfig(void)
   1927 {
   1928 	struct stat st;
   1929 	int oldsize = fontsize, oldscroll = scrollmax, newscroll;
   1930 	char oldfont[256];
   1931 
   1932 	if (stat(cfgpath, &st) < 0 || st.st_mtime == cfgmtime)
   1933 		return;
   1934 	snprintf(oldfont, sizeof oldfont, "%s", fontname);
   1935 	loadconfig();
   1936 	/* the ring is still the old size until it's moved */
   1937 	newscroll = scrollmax;
   1938 	scrollmax = oldscroll;
   1939 	if (newscroll != oldscroll)
   1940 		setscrollback(newscroll);
   1941 	if (forcesize > 3)
   1942 		fontsize = forcesize;
   1943 	setcolours();
   1944 	if (oldsize != fontsize || strcmp(oldfont, fontname)) {
   1945 		basesize = fontsize;
   1946 		zoom(fontsize);
   1947 	}
   1948 }
   1949 
   1950 static void
   1951 usage(void)
   1952 {
   1953 	fputs("usage: tyrmel [-T title] [-class name] [-geometry COLSxROWS] [-fs size] [-hold] [-e command ...]\n", stderr);
   1954 	exit(1);
   1955 }
   1956 
   1957 int
   1958 main(int argc, char *argv[])
   1959 {
   1960 	XSetWindowAttributes wa;
   1961 	XClassHint ch_ = { NULL, NULL };
   1962 	XEvent ev;
   1963 	fd_set fds;
   1964 	struct timeval tv;
   1965 	long last = 0, lastcheck = 0, now, pid;
   1966 	char cfgdir[1024];
   1967 	int i, xfd, status = 0;
   1968 
   1969 	for (i = 1; i < argc; i++) {
   1970 		if (!strcmp(argv[i], "-v")) {
   1971 			puts("tyrmel-" VERSION);
   1972 			return 0;
   1973 		} else if ((!strcmp(argv[i], "-T") || !strcmp(argv[i], "-title") || !strcmp(argv[i], "-t")) && i + 1 < argc)
   1974 			wtitle = argv[++i];
   1975 		else if ((!strcmp(argv[i], "-class") || !strcmp(argv[i], "-c")) && i + 1 < argc)
   1976 			wclass = argv[++i];
   1977 		else if (!strcmp(argv[i], "-name") && i + 1 < argc)
   1978 			wname = argv[++i];
   1979 		else if ((!strcmp(argv[i], "-geometry") || !strcmp(argv[i], "-g")) && i + 1 < argc)
   1980 			sscanf(argv[++i], "%dx%d", &geomcols, &geomrows);
   1981 		else if (!strcmp(argv[i], "-fs") && i + 1 < argc)
   1982 			forcesize = atoi(argv[++i]);
   1983 		else if (!strcmp(argv[i], "-hold"))
   1984 			holdopen = 1;
   1985 		else if (!strcmp(argv[i], "-e") && i + 1 < argc) {
   1986 			cmdargv = argv + i + 1;
   1987 			break;
   1988 		} else if (!strcmp(argv[i], "-ls") || !strcmp(argv[i], "+sb") || !strcmp(argv[i], "-sb"))
   1989 			;	/* xterm's, no matter here */
   1990 		else
   1991 			usage();
   1992 	}
   1993 	setlocale(LC_CTYPE, "");
   1994 	XSetLocaleModifiers("");
   1995 	if (!(dpy = XOpenDisplay(NULL)))
   1996 		die("can't open the display");
   1997 	scr = DefaultScreen(dpy);
   1998 	vis = DefaultVisual(dpy, scr);
   1999 	cmap = DefaultColormap(dpy, scr);
   2000 	depth = DefaultDepth(dpy, scr);
   2001 
   2002 	snprintf(cfgdir, sizeof cfgdir, "%s/.config/tyrmel", getenv("HOME") ? getenv("HOME") : ".");
   2003 	if (getenv("XDG_CONFIG_HOME") && *getenv("XDG_CONFIG_HOME"))
   2004 		snprintf(cfgdir, sizeof cfgdir, "%s/tyrmel", getenv("XDG_CONFIG_HOME"));
   2005 	/* ~/.config might not be there yet */
   2006 	snprintf(cfgpath, sizeof cfgpath, "%s", cfgdir);
   2007 	for (char *p = cfgpath + 1; *p; p++)
   2008 		if (*p == '/') {
   2009 			*p = '\0';
   2010 			mkdir(cfgpath, 0755);
   2011 			*p = '/';
   2012 		}
   2013 	mkdir(cfgdir, 0755);
   2014 	snprintf(cfgpath, sizeof cfgpath, "%s/config", cfgdir);
   2015 	loadconfig();
   2016 	if (forcesize > 3)
   2017 		fontsize = forcesize;
   2018 	basesize = fontsize;
   2019 	loadfonts(fontsize);
   2020 	cols = MAX(geomcols, 2), rows = MAX(geomrows, 1);
   2021 
   2022 	wa.background_pixel = BlackPixel(dpy, scr);
   2023 	wa.bit_gravity = NorthWestGravity;
   2024 	wa.event_mask = KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ExposureMask |
   2025 	                StructureNotifyMask | FocusChangeMask;
   2026 	win = XCreateWindow(dpy, RootWindow(dpy, scr), 0, 0, cols * cw, rows * ch, 0, depth, InputOutput, vis,
   2027 	                    CWBackPixel | CWBitGravity | CWEventMask, &wa);
   2028 	ch_.res_name = (char *)wname;
   2029 	ch_.res_class = (char *)wclass;
   2030 	XSetClassHint(dpy, win, &ch_);
   2031 	XStoreName(dpy, win, wtitle ? wtitle : cmdargv ? cmdargv[0] : "tyrmel");
   2032 	wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
   2033 	xclipboard = XInternAtom(dpy, "CLIPBOARD", False);
   2034 	xtargets = XInternAtom(dpy, "TARGETS", False);
   2035 	xutf8 = XInternAtom(dpy, "UTF8_STRING", False);
   2036 	xprop = XInternAtom(dpy, "TYRMEL_PASTE", False);
   2037 	netwmname = XInternAtom(dpy, "_NET_WM_NAME", False);
   2038 	netwmpid = XInternAtom(dpy, "_NET_WM_PID", False);
   2039 	XSetWMProtocols(dpy, win, &wmdelete, 1);
   2040 	pid = getpid();
   2041 	XChangeProperty(dpy, win, netwmpid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
   2042 	if (wtitle)
   2043 		XChangeProperty(dpy, win, netwmname, xutf8, 8, PropModeReplace, (unsigned char *)wtitle, strlen(wtitle));
   2044 	setsizehints();
   2045 	gc = XCreateGC(dpy, win, 0, NULL);
   2046 	if ((xim = XOpenIM(dpy, NULL, NULL, NULL)))
   2047 		xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win,
   2048 		                XNFocusWindow, win, NULL);
   2049 
   2050 	vt = vterm_new(rows, cols);
   2051 	vterm_set_utf8(vt, 1);
   2052 	vterm_output_set_callback(vt, ontermoutput, NULL);
   2053 	vs = vterm_obtain_screen(vt);
   2054 	vst = vterm_obtain_state(vt);
   2055 	vterm_screen_set_callbacks(vs, &screencb, NULL);
   2056 	vterm_screen_set_unrecognised_fallbacks(vs, &fallbacks, NULL);
   2057 	vterm_screen_enable_altscreen(vs, 1);
   2058 	vterm_screen_enable_reflow(vs, 1);
   2059 	vterm_screen_set_damage_merge(vs, VTERM_DAMAGE_SCROLL);
   2060 	vterm_state_set_bold_highbright(vst, 1);
   2061 	setcolours();
   2062 	vterm_screen_reset(vs, 1);
   2063 	if (scrollmax)
   2064 		sb = calloc(scrollmax, sizeof *sb);
   2065 
   2066 	resize(cols * cw, rows * ch);
   2067 	signal(SIGPIPE, SIG_IGN);
   2068 	spawn();
   2069 	XMapWindow(dpy, win);
   2070 	xfd = ConnectionNumber(dpy);
   2071 
   2072 	for (;;) {
   2073 		while (XPending(dpy)) {
   2074 			XNextEvent(dpy, &ev);
   2075 			if (XFilterEvent(&ev, None))
   2076 				continue;
   2077 			switch (ev.type) {
   2078 			case KeyPress: keypress(&ev.xkey); break;
   2079 			case ButtonPress: buttonpress(&ev.xbutton); break;
   2080 			case ButtonRelease: buttonrelease(&ev.xbutton); break;
   2081 			case MotionNotify: motion(&ev.xmotion); break;
   2082 			case Expose: if (!ev.xexpose.count) XCopyArea(dpy, buf, win, gc, 0, 0, ww, wh, 0, 0); break;
   2083 			case ConfigureNotify: resize(ev.xconfigure.width, ev.xconfigure.height); break;
   2084 			case SelectionRequest: selectionrequest(&ev.xselectionrequest); break;
   2085 			case SelectionNotify: selectionnotify(&ev.xselection); break;
   2086 			case SelectionClear: break;
   2087 			case FocusIn:
   2088 			case FocusOut:
   2089 				focused = ev.type == FocusIn;
   2090 				if (xic)
   2091 					(focused ? XSetICFocus : XUnsetICFocus)(xic);
   2092 				if (focused)
   2093 					vterm_state_focus_in(vst);
   2094 				else
   2095 					vterm_state_focus_out(vst);
   2096 				if (focused) {
   2097 					XWMHints *h = XGetWMHints(dpy, win);
   2098 
   2099 					if (h && (h->flags & XUrgencyHint)) {
   2100 						h->flags &= ~XUrgencyHint;
   2101 						XSetWMHints(dpy, win, h);
   2102 					}
   2103 					if (h)
   2104 						XFree(h);
   2105 				}
   2106 				dirty = 1;
   2107 				break;
   2108 			case ClientMessage:
   2109 				if ((Atom)ev.xclient.data.l[0] == wmdelete) {
   2110 					kill(child, SIGHUP);
   2111 					return 0;
   2112 				}
   2113 				break;
   2114 			}
   2115 		}
   2116 		now = ms();
   2117 		if (dirty && now - last >= 16) {
   2118 			redraw();
   2119 			last = now;
   2120 		}
   2121 		XFlush(dpy);
   2122 		FD_ZERO(&fds);
   2123 		FD_SET(xfd, &fds);
   2124 		if (ptyfd >= 0)
   2125 			FD_SET(ptyfd, &fds);
   2126 		tv.tv_sec = dirty ? 0 : 2;
   2127 		tv.tv_usec = dirty ? 16000 : 0;
   2128 		if (select(MAX(xfd, ptyfd) + 1, &fds, NULL, NULL, &tv) < 0 && errno != EINTR)
   2129 			die("select");
   2130 		if (ptyfd >= 0 && FD_ISSET(ptyfd, &fds) && readpty() < 0) {
   2131 			waitpid(child, &status, WNOHANG);
   2132 			close(ptyfd);
   2133 			ptyfd = -1;
   2134 			if (!holdopen)
   2135 				break;
   2136 		}
   2137 		/* the settings file, every two seconds */
   2138 		if ((now = ms()) - lastcheck > 2000) {
   2139 			checkconfig();
   2140 			lastcheck = now;
   2141 		}
   2142 	}
   2143 	if (dirty)
   2144 		redraw();
   2145 	XCloseDisplay(dpy);
   2146 	return WIFEXITED(status) ? WEXITSTATUS(status) : 0;
   2147 }