st

My custom build of st terminal.
git clone https://git.mtkn.jp/st
Log | Files | Refs | README | LICENSE

x.c.orig (50573B)


      1 /* See LICENSE for license details. */
      2 #include <errno.h>
      3 #include <math.h>
      4 #include <limits.h>
      5 #include <locale.h>
      6 #include <signal.h>
      7 #include <sys/select.h>
      8 #include <time.h>
      9 #include <unistd.h>
     10 #include <libgen.h>
     11 #include <X11/Xatom.h>
     12 #include <X11/Xlib.h>
     13 #include <X11/cursorfont.h>
     14 #include <X11/keysym.h>
     15 #include <X11/Xft/Xft.h>
     16 #include <X11/XKBlib.h>
     17 
     18 char *argv0;
     19 #include "arg.h"
     20 #include "st.h"
     21 #include "win.h"
     22 
     23 /* types used in config.h */
     24 typedef struct {
     25 	uint mod;
     26 	KeySym keysym;
     27 	void (*func)(const Arg *);
     28 	const Arg arg;
     29 } Shortcut;
     30 
     31 typedef struct {
     32 	uint mod;
     33 	uint button;
     34 	void (*func)(const Arg *);
     35 	const Arg arg;
     36 	uint  release;
     37 } MouseShortcut;
     38 
     39 typedef struct {
     40 	KeySym k;
     41 	uint mask;
     42 	char *s;
     43 	/* three-valued logic variables: 0 indifferent, 1 on, -1 off */
     44 	signed char appkey;    /* application keypad */
     45 	signed char appcursor; /* application cursor */
     46 } Key;
     47 
     48 /* X modifiers */
     49 #define XK_ANY_MOD    UINT_MAX
     50 #define XK_NO_MOD     0
     51 #define XK_SWITCH_MOD (1<<13|1<<14)
     52 
     53 /* function definitions used in config.h */
     54 static void clipcopy(const Arg *);
     55 static void clippaste(const Arg *);
     56 static void numlock(const Arg *);
     57 static void selpaste(const Arg *);
     58 static void zoom(const Arg *);
     59 static void zoomabs(const Arg *);
     60 static void zoomreset(const Arg *);
     61 static void ttysend(const Arg *);
     62 
     63 /* config.h for applying patches and the configuration. */
     64 #include "config.h"
     65 
     66 /* XEMBED messages */
     67 #define XEMBED_FOCUS_IN  4
     68 #define XEMBED_FOCUS_OUT 5
     69 
     70 /* macros */
     71 #define IS_SET(flag)		((win.mode & (flag)) != 0)
     72 #define TRUERED(x)		(((x) & 0xff0000) >> 8)
     73 #define TRUEGREEN(x)		(((x) & 0xff00))
     74 #define TRUEBLUE(x)		(((x) & 0xff) << 8)
     75 
     76 typedef XftDraw *Draw;
     77 typedef XftColor Color;
     78 typedef XftGlyphFontSpec GlyphFontSpec;
     79 
     80 /* Purely graphic info */
     81 typedef struct {
     82 	int tw, th; /* tty width and height */
     83 	int w, h; /* window width and height */
     84 	int ch; /* char height */
     85 	int cw; /* char width  */
     86 	int mode; /* window state/mode flags */
     87 	int cursor; /* cursor style */
     88 } TermWindow;
     89 
     90 typedef struct {
     91 	Display *dpy;
     92 	Colormap cmap;
     93 	Window win;
     94 	Drawable buf;
     95 	GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
     96 	Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
     97 	struct {
     98 		XIM xim;
     99 		XIC xic;
    100 		XPoint spot;
    101 		XVaNestedList spotlist;
    102 	} ime;
    103 	Draw draw;
    104 	Visual *vis;
    105 	XSetWindowAttributes attrs;
    106 	int scr;
    107 	int isfixed; /* is fixed geometry? */
    108 	int l, t; /* left and top offset */
    109 	int gm; /* geometry mask */
    110 } XWindow;
    111 
    112 typedef struct {
    113 	Atom xtarget;
    114 	char *primary, *clipboard;
    115 	struct timespec tclick1;
    116 	struct timespec tclick2;
    117 } XSelection;
    118 
    119 /* Font structure */
    120 #define Font Font_
    121 typedef struct {
    122 	int height;
    123 	int width;
    124 	int ascent;
    125 	int descent;
    126 	int badslant;
    127 	int badweight;
    128 	short lbearing;
    129 	short rbearing;
    130 	XftFont *match;
    131 	FcFontSet *set;
    132 	FcPattern *pattern;
    133 } Font;
    134 
    135 /* Drawing Context */
    136 typedef struct {
    137 	Color *col;
    138 	size_t collen;
    139 	Font font, bfont, ifont, ibfont;
    140 	GC gc;
    141 } DC;
    142 
    143 static inline ushort sixd_to_16bit(int);
    144 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
    145 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
    146 static void xdrawglyph(Glyph, int, int);
    147 static void xclear(int, int, int, int);
    148 static int xgeommasktogravity(int);
    149 static int ximopen(Display *);
    150 static void ximinstantiate(Display *, XPointer, XPointer);
    151 static void ximdestroy(XIM, XPointer, XPointer);
    152 static int xicdestroy(XIC, XPointer, XPointer);
    153 static void xinit(int, int);
    154 static void cresize(int, int);
    155 static void xresize(int, int);
    156 static void xhints(void);
    157 static int xloadcolor(int, const char *, Color *);
    158 static int xloadfont(Font *, FcPattern *);
    159 static void xloadfonts(const char *, double);
    160 static int xloadsparefont(FcPattern *, int);
    161 static void xloadsparefonts(void);
    162 static void xunloadfont(Font *);
    163 static void xunloadfonts(void);
    164 static void xsetenv(void);
    165 static void xseturgency(int);
    166 static int evcol(XEvent *);
    167 static int evrow(XEvent *);
    168 
    169 static void expose(XEvent *);
    170 static void visibility(XEvent *);
    171 static void unmap(XEvent *);
    172 static void kpress(XEvent *);
    173 static void cmessage(XEvent *);
    174 static void resize(XEvent *);
    175 static void focus(XEvent *);
    176 static uint buttonmask(uint);
    177 static int mouseaction(XEvent *, uint);
    178 static void brelease(XEvent *);
    179 static void bpress(XEvent *);
    180 static void bmotion(XEvent *);
    181 static void propnotify(XEvent *);
    182 static void selnotify(XEvent *);
    183 static void selclear_(XEvent *);
    184 static void selrequest(XEvent *);
    185 static void setsel(char *, Time);
    186 static void mousesel(XEvent *, int);
    187 static void mousereport(XEvent *);
    188 static char *kmap(KeySym, uint);
    189 static int match(uint, uint);
    190 
    191 static void run(void);
    192 static void usage(void);
    193 
    194 static void (*handler[LASTEvent])(XEvent *) = {
    195 	[KeyPress] = kpress,
    196 	[ClientMessage] = cmessage,
    197 	[ConfigureNotify] = resize,
    198 	[VisibilityNotify] = visibility,
    199 	[UnmapNotify] = unmap,
    200 	[Expose] = expose,
    201 	[FocusIn] = focus,
    202 	[FocusOut] = focus,
    203 	[MotionNotify] = bmotion,
    204 	[ButtonPress] = bpress,
    205 	[ButtonRelease] = brelease,
    206 /*
    207  * Uncomment if you want the selection to disappear when you select something
    208  * different in another window.
    209  */
    210 /*	[SelectionClear] = selclear_, */
    211 	[SelectionNotify] = selnotify,
    212 /*
    213  * PropertyNotify is only turned on when there is some INCR transfer happening
    214  * for the selection retrieval.
    215  */
    216 	[PropertyNotify] = propnotify,
    217 	[SelectionRequest] = selrequest,
    218 };
    219 
    220 /* Globals */
    221 static DC dc;
    222 static XWindow xw;
    223 static XSelection xsel;
    224 static TermWindow win;
    225 
    226 /* Font Ring Cache */
    227 enum {
    228 	FRC_NORMAL,
    229 	FRC_ITALIC,
    230 	FRC_BOLD,
    231 	FRC_ITALICBOLD
    232 };
    233 
    234 typedef struct {
    235 	XftFont *font;
    236 	int flags;
    237 	Rune unicodep;
    238 } Fontcache;
    239 
    240 /* Fontcache is an array now. A new font will be appended to the array. */
    241 static Fontcache *frc = NULL;
    242 static int frclen = 0;
    243 static int frccap = 0;
    244 static char *usedfont = NULL;
    245 static double usedfontsize = 0;
    246 static double defaultfontsize = 0;
    247 
    248 static char *opt_class = NULL;
    249 static char **opt_cmd  = NULL;
    250 static char *opt_embed = NULL;
    251 static char *opt_font  = NULL;
    252 static char *opt_io    = NULL;
    253 static char *opt_line  = NULL;
    254 static char *opt_name  = NULL;
    255 static char *opt_title = NULL;
    256 
    257 static uint buttons; /* bit field of pressed buttons */
    258 
    259 void
    260 clipcopy(const Arg *dummy)
    261 {
    262 	Atom clipboard;
    263 
    264 	free(xsel.clipboard);
    265 	xsel.clipboard = NULL;
    266 
    267 	if (xsel.primary != NULL) {
    268 		xsel.clipboard = xstrdup(xsel.primary);
    269 		clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
    270 		XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
    271 	}
    272 }
    273 
    274 void
    275 clippaste(const Arg *dummy)
    276 {
    277 	Atom clipboard;
    278 
    279 	clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
    280 	XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
    281 			xw.win, CurrentTime);
    282 }
    283 
    284 void
    285 selpaste(const Arg *dummy)
    286 {
    287 	XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
    288 			xw.win, CurrentTime);
    289 }
    290 
    291 void
    292 numlock(const Arg *dummy)
    293 {
    294 	win.mode ^= MODE_NUMLOCK;
    295 }
    296 
    297 void
    298 zoom(const Arg *arg)
    299 {
    300 	Arg larg;
    301 
    302 	larg.f = usedfontsize + arg->f;
    303 	zoomabs(&larg);
    304 }
    305 
    306 void
    307 zoomabs(const Arg *arg)
    308 {
    309 	xunloadfonts();
    310 	xloadfonts(usedfont, arg->f);
    311 	xloadsparefonts();
    312 	cresize(0, 0);
    313 	redraw();
    314 	xhints();
    315 }
    316 
    317 void
    318 zoomreset(const Arg *arg)
    319 {
    320 	Arg larg;
    321 
    322 	if (defaultfontsize > 0) {
    323 		larg.f = defaultfontsize;
    324 		zoomabs(&larg);
    325 	}
    326 }
    327 
    328 void
    329 ttysend(const Arg *arg)
    330 {
    331 	ttywrite(arg->s, strlen(arg->s), 1);
    332 }
    333 
    334 int
    335 evcol(XEvent *e)
    336 {
    337 	int x = e->xbutton.x - borderpx;
    338 	LIMIT(x, 0, win.tw - 1);
    339 	return x / win.cw;
    340 }
    341 
    342 int
    343 evrow(XEvent *e)
    344 {
    345 	int y = e->xbutton.y - borderpx;
    346 	LIMIT(y, 0, win.th - 1);
    347 	return y / win.ch;
    348 }
    349 
    350 void
    351 mousesel(XEvent *e, int done)
    352 {
    353 	int type, seltype = SEL_REGULAR;
    354 	uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
    355 
    356 	for (type = 1; type < LEN(selmasks); ++type) {
    357 		if (match(selmasks[type], state)) {
    358 			seltype = type;
    359 			break;
    360 		}
    361 	}
    362 	selextend(evcol(e), evrow(e), seltype, done);
    363 	if (done)
    364 		setsel(getsel(), e->xbutton.time);
    365 }
    366 
    367 void
    368 mousereport(XEvent *e)
    369 {
    370 	int len, btn, code;
    371 	int x = evcol(e), y = evrow(e);
    372 	int state = e->xbutton.state;
    373 	char buf[40];
    374 	static int ox, oy;
    375 
    376 	if (e->type == MotionNotify) {
    377 		if (x == ox && y == oy)
    378 			return;
    379 		if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
    380 			return;
    381 		/* MODE_MOUSEMOTION: no reporting if no button is pressed */
    382 		if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
    383 			return;
    384 		/* Set btn to lowest-numbered pressed button, or 12 if no
    385 		 * buttons are pressed. */
    386 		for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++)
    387 			;
    388 		code = 32;
    389 	} else {
    390 		btn = e->xbutton.button;
    391 		/* Only buttons 1 through 11 can be encoded */
    392 		if (btn < 1 || btn > 11)
    393 			return;
    394 		if (e->type == ButtonRelease) {
    395 			/* MODE_MOUSEX10: no button release reporting */
    396 			if (IS_SET(MODE_MOUSEX10))
    397 				return;
    398 			/* Don't send release events for the scroll wheel */
    399 			if (btn == 4 || btn == 5)
    400 				return;
    401 		}
    402 		code = 0;
    403 	}
    404 
    405 	ox = x;
    406 	oy = y;
    407 
    408 	/* Encode btn into code. If no button is pressed for a motion event in
    409 	 * MODE_MOUSEMANY, then encode it as a release. */
    410 	if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12)
    411 		code += 3;
    412 	else if (btn >= 8)
    413 		code += 128 + btn - 8;
    414 	else if (btn >= 4)
    415 		code += 64 + btn - 4;
    416 	else
    417 		code += btn - 1;
    418 
    419 	if (!IS_SET(MODE_MOUSEX10)) {
    420 		code += ((state & ShiftMask  ) ?  4 : 0)
    421 		      + ((state & Mod1Mask   ) ?  8 : 0) /* meta key: alt */
    422 		      + ((state & ControlMask) ? 16 : 0);
    423 	}
    424 
    425 	if (IS_SET(MODE_MOUSESGR)) {
    426 		len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
    427 				code, x+1, y+1,
    428 				e->type == ButtonRelease ? 'm' : 'M');
    429 	} else if (x < 223 && y < 223) {
    430 		len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
    431 				32+code, 32+x+1, 32+y+1);
    432 	} else {
    433 		return;
    434 	}
    435 
    436 	ttywrite(buf, len, 0);
    437 }
    438 
    439 uint
    440 buttonmask(uint button)
    441 {
    442 	return button == Button1 ? Button1Mask
    443 	     : button == Button2 ? Button2Mask
    444 	     : button == Button3 ? Button3Mask
    445 	     : button == Button4 ? Button4Mask
    446 	     : button == Button5 ? Button5Mask
    447 	     : 0;
    448 }
    449 
    450 int
    451 mouseaction(XEvent *e, uint release)
    452 {
    453 	MouseShortcut *ms;
    454 
    455 	/* ignore Button<N>mask for Button<N> - it's set on release */
    456 	uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
    457 
    458 	for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
    459 		if (ms->release == release &&
    460 		    ms->button == e->xbutton.button &&
    461 		    (match(ms->mod, state) ||  /* exact or forced */
    462 		     match(ms->mod, state & ~forcemousemod))) {
    463 			ms->func(&(ms->arg));
    464 			return 1;
    465 		}
    466 	}
    467 
    468 	return 0;
    469 }
    470 
    471 void
    472 bpress(XEvent *e)
    473 {
    474 	int btn = e->xbutton.button;
    475 	struct timespec now;
    476 	int snap;
    477 
    478 	if (1 <= btn && btn <= 11)
    479 		buttons |= 1 << (btn-1);
    480 
    481 	if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
    482 		mousereport(e);
    483 		return;
    484 	}
    485 
    486 	if (mouseaction(e, 0))
    487 		return;
    488 
    489 	if (btn == Button1) {
    490 		/*
    491 		 * If the user clicks below predefined timeouts specific
    492 		 * snapping behaviour is exposed.
    493 		 */
    494 		clock_gettime(CLOCK_MONOTONIC, &now);
    495 		if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
    496 			snap = SNAP_LINE;
    497 		} else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
    498 			snap = SNAP_WORD;
    499 		} else {
    500 			snap = 0;
    501 		}
    502 		xsel.tclick2 = xsel.tclick1;
    503 		xsel.tclick1 = now;
    504 
    505 		selstart(evcol(e), evrow(e), snap);
    506 	}
    507 }
    508 
    509 void
    510 propnotify(XEvent *e)
    511 {
    512 	XPropertyEvent *xpev;
    513 	Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
    514 
    515 	xpev = &e->xproperty;
    516 	if (xpev->state == PropertyNewValue &&
    517 			(xpev->atom == XA_PRIMARY ||
    518 			 xpev->atom == clipboard)) {
    519 		selnotify(e);
    520 	}
    521 }
    522 
    523 void
    524 selnotify(XEvent *e)
    525 {
    526 	ulong nitems, ofs, rem;
    527 	int format;
    528 	uchar *data, *last, *repl;
    529 	Atom type, incratom, property = None;
    530 
    531 	incratom = XInternAtom(xw.dpy, "INCR", 0);
    532 
    533 	ofs = 0;
    534 	if (e->type == SelectionNotify)
    535 		property = e->xselection.property;
    536 	else if (e->type == PropertyNotify)
    537 		property = e->xproperty.atom;
    538 
    539 	if (property == None)
    540 		return;
    541 
    542 	do {
    543 		if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
    544 					BUFSIZ/4, False, AnyPropertyType,
    545 					&type, &format, &nitems, &rem,
    546 					&data)) {
    547 			fprintf(stderr, "Clipboard allocation failed\n");
    548 			return;
    549 		}
    550 
    551 		if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
    552 			/*
    553 			 * If there is some PropertyNotify with no data, then
    554 			 * this is the signal of the selection owner that all
    555 			 * data has been transferred. We won't need to receive
    556 			 * PropertyNotify events anymore.
    557 			 */
    558 			MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
    559 			XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
    560 					&xw.attrs);
    561 		}
    562 
    563 		if (type == incratom) {
    564 			/*
    565 			 * Activate the PropertyNotify events so we receive
    566 			 * when the selection owner does send us the next
    567 			 * chunk of data.
    568 			 */
    569 			MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
    570 			XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
    571 					&xw.attrs);
    572 
    573 			/*
    574 			 * Deleting the property is the transfer start signal.
    575 			 */
    576 			XDeleteProperty(xw.dpy, xw.win, (int)property);
    577 			continue;
    578 		}
    579 
    580 		/*
    581 		 * As seen in getsel:
    582 		 * Line endings are inconsistent in the terminal and GUI world
    583 		 * copy and pasting. When receiving some selection data,
    584 		 * replace all '\n' with '\r'.
    585 		 * FIXME: Fix the computer world.
    586 		 */
    587 		repl = data;
    588 		last = data + nitems * format / 8;
    589 		while ((repl = memchr(repl, '\n', last - repl))) {
    590 			*repl++ = '\r';
    591 		}
    592 
    593 		if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
    594 			ttywrite("\033[200~", 6, 0);
    595 		ttywrite((char *)data, nitems * format / 8, 1);
    596 		if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
    597 			ttywrite("\033[201~", 6, 0);
    598 		XFree(data);
    599 		/* number of 32-bit chunks returned */
    600 		ofs += nitems * format / 32;
    601 	} while (rem > 0);
    602 
    603 	/*
    604 	 * Deleting the property again tells the selection owner to send the
    605 	 * next data chunk in the property.
    606 	 */
    607 	XDeleteProperty(xw.dpy, xw.win, (int)property);
    608 }
    609 
    610 void
    611 xclipcopy(void)
    612 {
    613 	clipcopy(NULL);
    614 }
    615 
    616 void
    617 selclear_(XEvent *e)
    618 {
    619 	selclear();
    620 }
    621 
    622 void
    623 selrequest(XEvent *e)
    624 {
    625 	XSelectionRequestEvent *xsre;
    626 	XSelectionEvent xev;
    627 	Atom xa_targets, string, clipboard;
    628 	char *seltext;
    629 
    630 	xsre = (XSelectionRequestEvent *) e;
    631 	xev.type = SelectionNotify;
    632 	xev.requestor = xsre->requestor;
    633 	xev.selection = xsre->selection;
    634 	xev.target = xsre->target;
    635 	xev.time = xsre->time;
    636 	if (xsre->property == None)
    637 		xsre->property = xsre->target;
    638 
    639 	/* reject */
    640 	xev.property = None;
    641 
    642 	xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
    643 	if (xsre->target == xa_targets) {
    644 		/* respond with the supported type */
    645 		string = xsel.xtarget;
    646 		XChangeProperty(xsre->display, xsre->requestor, xsre->property,
    647 				XA_ATOM, 32, PropModeReplace,
    648 				(uchar *) &string, 1);
    649 		xev.property = xsre->property;
    650 	} else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
    651 		/*
    652 		 * xith XA_STRING non ascii characters may be incorrect in the
    653 		 * requestor. It is not our problem, use utf8.
    654 		 */
    655 		clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
    656 		if (xsre->selection == XA_PRIMARY) {
    657 			seltext = xsel.primary;
    658 		} else if (xsre->selection == clipboard) {
    659 			seltext = xsel.clipboard;
    660 		} else {
    661 			fprintf(stderr,
    662 				"Unhandled clipboard selection 0x%lx\n",
    663 				xsre->selection);
    664 			return;
    665 		}
    666 		if (seltext != NULL) {
    667 			XChangeProperty(xsre->display, xsre->requestor,
    668 					xsre->property, xsre->target,
    669 					8, PropModeReplace,
    670 					(uchar *)seltext, strlen(seltext));
    671 			xev.property = xsre->property;
    672 		}
    673 	}
    674 
    675 	/* all done, send a notification to the listener */
    676 	if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
    677 		fprintf(stderr, "Error sending SelectionNotify event\n");
    678 }
    679 
    680 void
    681 setsel(char *str, Time t)
    682 {
    683 	if (!str)
    684 		return;
    685 
    686 	free(xsel.primary);
    687 	xsel.primary = str;
    688 
    689 	XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
    690 	if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
    691 		selclear();
    692 }
    693 
    694 void
    695 xsetsel(char *str)
    696 {
    697 	setsel(str, CurrentTime);
    698 }
    699 
    700 void
    701 brelease(XEvent *e)
    702 {
    703 	int btn = e->xbutton.button;
    704 
    705 	if (1 <= btn && btn <= 11)
    706 		buttons &= ~(1 << (btn-1));
    707 
    708 	if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
    709 		mousereport(e);
    710 		return;
    711 	}
    712 
    713 	if (mouseaction(e, 1))
    714 		return;
    715 	if (btn == Button1)
    716 		mousesel(e, 1);
    717 }
    718 
    719 void
    720 bmotion(XEvent *e)
    721 {
    722 	if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
    723 		mousereport(e);
    724 		return;
    725 	}
    726 
    727 	mousesel(e, 0);
    728 }
    729 
    730 void
    731 cresize(int width, int height)
    732 {
    733 	int col, row;
    734 
    735 	if (width != 0)
    736 		win.w = width;
    737 	if (height != 0)
    738 		win.h = height;
    739 
    740 	col = (win.w - 2 * borderpx) / win.cw;
    741 	row = (win.h - 2 * borderpx) / win.ch;
    742 	col = MAX(1, col);
    743 	row = MAX(1, row);
    744 
    745 	tresize(col, row);
    746 	xresize(col, row);
    747 	ttyresize(win.tw, win.th);
    748 }
    749 
    750 void
    751 xresize(int col, int row)
    752 {
    753 	win.tw = col * win.cw;
    754 	win.th = row * win.ch;
    755 
    756 	XFreePixmap(xw.dpy, xw.buf);
    757 	xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
    758 			DefaultDepth(xw.dpy, xw.scr));
    759 	XftDrawChange(xw.draw, xw.buf);
    760 	xclear(0, 0, win.w, win.h);
    761 
    762 	/* resize to new width */
    763 	xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
    764 }
    765 
    766 ushort
    767 sixd_to_16bit(int x)
    768 {
    769 	return x == 0 ? 0 : 0x3737 + 0x2828 * x;
    770 }
    771 
    772 int
    773 xloadcolor(int i, const char *name, Color *ncolor)
    774 {
    775 	XRenderColor color = { .alpha = 0xffff };
    776 
    777 	if (!name) {
    778 		if (BETWEEN(i, 16, 255)) { /* 256 color */
    779 			if (i < 6*6*6+16) { /* same colors as xterm */
    780 				color.red   = sixd_to_16bit( ((i-16)/36)%6 );
    781 				color.green = sixd_to_16bit( ((i-16)/6) %6 );
    782 				color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
    783 			} else { /* greyscale */
    784 				color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
    785 				color.green = color.blue = color.red;
    786 			}
    787 			return XftColorAllocValue(xw.dpy, xw.vis,
    788 			                          xw.cmap, &color, ncolor);
    789 		} else
    790 			name = colorname[i];
    791 	}
    792 
    793 	return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
    794 }
    795 
    796 void
    797 xloadcols(void)
    798 {
    799 	int i;
    800 	static int loaded;
    801 	Color *cp;
    802 
    803 	if (loaded) {
    804 		for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
    805 			XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
    806 	} else {
    807 		dc.collen = MAX(LEN(colorname), 256);
    808 		dc.col = xmalloc(dc.collen * sizeof(Color));
    809 	}
    810 
    811 	for (i = 0; i < dc.collen; i++)
    812 		if (!xloadcolor(i, NULL, &dc.col[i])) {
    813 			if (colorname[i])
    814 				die("could not allocate color '%s'\n", colorname[i]);
    815 			else
    816 				die("could not allocate color %d\n", i);
    817 		}
    818 	loaded = 1;
    819 }
    820 
    821 int
    822 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
    823 {
    824 	if (!BETWEEN(x, 0, dc.collen))
    825 		return 1;
    826 
    827 	*r = dc.col[x].color.red >> 8;
    828 	*g = dc.col[x].color.green >> 8;
    829 	*b = dc.col[x].color.blue >> 8;
    830 
    831 	return 0;
    832 }
    833 
    834 int
    835 xsetcolorname(int x, const char *name)
    836 {
    837 	Color ncolor;
    838 
    839 	if (!BETWEEN(x, 0, dc.collen))
    840 		return 1;
    841 
    842 	if (!xloadcolor(x, name, &ncolor))
    843 		return 1;
    844 
    845 	XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
    846 	dc.col[x] = ncolor;
    847 
    848 	return 0;
    849 }
    850 
    851 /*
    852  * Absolute coordinates.
    853  */
    854 void
    855 xclear(int x1, int y1, int x2, int y2)
    856 {
    857 	XftDrawRect(xw.draw,
    858 			&dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
    859 			x1, y1, x2-x1, y2-y1);
    860 }
    861 
    862 void
    863 xhints(void)
    864 {
    865 	XClassHint class = {opt_name ? opt_name : termname,
    866 	                    opt_class ? opt_class : termname};
    867 	XWMHints wm = {.flags = InputHint, .input = 1};
    868 	XSizeHints *sizeh;
    869 
    870 	sizeh = XAllocSizeHints();
    871 
    872 	sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
    873 	sizeh->height = win.h;
    874 	sizeh->width = win.w;
    875 	sizeh->height_inc = win.ch;
    876 	sizeh->width_inc = win.cw;
    877 	sizeh->base_height = 2 * borderpx;
    878 	sizeh->base_width = 2 * borderpx;
    879 	sizeh->min_height = win.ch + 2 * borderpx;
    880 	sizeh->min_width = win.cw + 2 * borderpx;
    881 	if (xw.isfixed) {
    882 		sizeh->flags |= PMaxSize;
    883 		sizeh->min_width = sizeh->max_width = win.w;
    884 		sizeh->min_height = sizeh->max_height = win.h;
    885 	}
    886 	if (xw.gm & (XValue|YValue)) {
    887 		sizeh->flags |= USPosition | PWinGravity;
    888 		sizeh->x = xw.l;
    889 		sizeh->y = xw.t;
    890 		sizeh->win_gravity = xgeommasktogravity(xw.gm);
    891 	}
    892 
    893 	XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
    894 			&class);
    895 	XFree(sizeh);
    896 }
    897 
    898 int
    899 xgeommasktogravity(int mask)
    900 {
    901 	switch (mask & (XNegative|YNegative)) {
    902 	case 0:
    903 		return NorthWestGravity;
    904 	case XNegative:
    905 		return NorthEastGravity;
    906 	case YNegative:
    907 		return SouthWestGravity;
    908 	}
    909 
    910 	return SouthEastGravity;
    911 }
    912 
    913 int
    914 xloadfont(Font *f, FcPattern *pattern)
    915 {
    916 	FcPattern *configured;
    917 	FcPattern *match;
    918 	FcResult result;
    919 	XGlyphInfo extents;
    920 	int wantattr, haveattr;
    921 
    922 	/*
    923 	 * Manually configure instead of calling XftMatchFont
    924 	 * so that we can use the configured pattern for
    925 	 * "missing glyph" lookups.
    926 	 */
    927 	configured = FcPatternDuplicate(pattern);
    928 	if (!configured)
    929 		return 1;
    930 
    931 	FcConfigSubstitute(NULL, configured, FcMatchPattern);
    932 	XftDefaultSubstitute(xw.dpy, xw.scr, configured);
    933 
    934 	match = FcFontMatch(NULL, configured, &result);
    935 	if (!match) {
    936 		FcPatternDestroy(configured);
    937 		return 1;
    938 	}
    939 
    940 	if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
    941 		FcPatternDestroy(configured);
    942 		FcPatternDestroy(match);
    943 		return 1;
    944 	}
    945 
    946 	if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
    947 	    XftResultMatch)) {
    948 		/*
    949 		 * Check if xft was unable to find a font with the appropriate
    950 		 * slant but gave us one anyway. Try to mitigate.
    951 		 */
    952 		if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
    953 		    &haveattr) != XftResultMatch) || haveattr < wantattr) {
    954 			f->badslant = 1;
    955 			fputs("font slant does not match\n", stderr);
    956 		}
    957 	}
    958 
    959 	if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
    960 	    XftResultMatch)) {
    961 		if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
    962 		    &haveattr) != XftResultMatch) || haveattr != wantattr) {
    963 			f->badweight = 1;
    964 			fputs("font weight does not match\n", stderr);
    965 		}
    966 	}
    967 
    968 	XftTextExtentsUtf8(xw.dpy, f->match,
    969 		(const FcChar8 *) ascii_printable,
    970 		strlen(ascii_printable), &extents);
    971 
    972 	f->set = NULL;
    973 	f->pattern = configured;
    974 
    975 	f->ascent = f->match->ascent;
    976 	f->descent = f->match->descent;
    977 	f->lbearing = 0;
    978 	f->rbearing = f->match->max_advance_width;
    979 
    980 	f->height = f->ascent + f->descent;
    981 	f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
    982 
    983 	return 0;
    984 }
    985 
    986 void
    987 xloadfonts(const char *fontstr, double fontsize)
    988 {
    989 	FcPattern *pattern;
    990 	double fontval;
    991 
    992 	if (fontstr[0] == '-')
    993 		pattern = XftXlfdParse(fontstr, False, False);
    994 	else
    995 		pattern = FcNameParse((const FcChar8 *)fontstr);
    996 
    997 	if (!pattern)
    998 		die("can't open font %s\n", fontstr);
    999 
   1000 	if (fontsize > 1) {
   1001 		FcPatternDel(pattern, FC_PIXEL_SIZE);
   1002 		FcPatternDel(pattern, FC_SIZE);
   1003 		FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
   1004 		usedfontsize = fontsize;
   1005 	} else {
   1006 		if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
   1007 				FcResultMatch) {
   1008 			usedfontsize = fontval;
   1009 		} else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
   1010 				FcResultMatch) {
   1011 			usedfontsize = -1;
   1012 		} else {
   1013 			/*
   1014 			 * Default font size is 12, if none given. This is to
   1015 			 * have a known usedfontsize value.
   1016 			 */
   1017 			FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
   1018 			usedfontsize = 12;
   1019 		}
   1020 		defaultfontsize = usedfontsize;
   1021 	}
   1022 
   1023 	if (xloadfont(&dc.font, pattern))
   1024 		die("can't open font %s\n", fontstr);
   1025 
   1026 	if (usedfontsize < 0) {
   1027 		FcPatternGetDouble(dc.font.match->pattern,
   1028 		                   FC_PIXEL_SIZE, 0, &fontval);
   1029 		usedfontsize = fontval;
   1030 		if (fontsize == 0)
   1031 			defaultfontsize = fontval;
   1032 	}
   1033 
   1034 	/* Setting character width and height. */
   1035 	win.cw = ceilf(dc.font.width * cwscale);
   1036 	win.ch = ceilf(dc.font.height * chscale);
   1037 
   1038 	FcPatternDel(pattern, FC_SLANT);
   1039 	FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
   1040 	if (xloadfont(&dc.ifont, pattern))
   1041 		die("can't open font %s\n", fontstr);
   1042 
   1043 	FcPatternDel(pattern, FC_WEIGHT);
   1044 	FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
   1045 	if (xloadfont(&dc.ibfont, pattern))
   1046 		die("can't open font %s\n", fontstr);
   1047 
   1048 	FcPatternDel(pattern, FC_SLANT);
   1049 	FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
   1050 	if (xloadfont(&dc.bfont, pattern))
   1051 		die("can't open font %s\n", fontstr);
   1052 
   1053 	FcPatternDestroy(pattern);
   1054 }
   1055 
   1056 int
   1057 xloadsparefont(FcPattern *pattern, int flags)
   1058 {
   1059 	FcPattern *match;
   1060 	FcResult result;
   1061 
   1062 	match = FcFontMatch(NULL, pattern, &result);
   1063 	if (!match) {
   1064 		return 1;
   1065 	}
   1066 
   1067 	if (!(frc[frclen].font = XftFontOpenPattern(xw.dpy, match))) {
   1068 		FcPatternDestroy(match);
   1069 		return 1;
   1070 	}
   1071 
   1072 	frc[frclen].flags = flags;
   1073 	/* Believe U+0000 glyph will present in each default font */
   1074 	frc[frclen].unicodep = 0;
   1075 	frclen++;
   1076 
   1077 	return 0;
   1078 }
   1079 
   1080 void
   1081 xloadsparefonts(void)
   1082 {
   1083 	FcPattern *pattern;
   1084 	double sizeshift, fontval;
   1085 	int fc;
   1086 	char **fp;
   1087 
   1088 	if (frclen != 0)
   1089 		die("can't embed spare fonts. cache isn't empty");
   1090 
   1091 	/* Calculate count of spare fonts */
   1092 	fc = sizeof(font2) / sizeof(*font2);
   1093 	if (fc == 0)
   1094 		return;
   1095 
   1096 	/* Allocate memory for cache entries. */
   1097 	if (frccap < 4 * fc) {
   1098 		frccap += 4 * fc - frccap;
   1099 		frc = xrealloc(frc, frccap * sizeof(Fontcache));
   1100 	}
   1101 
   1102 	for (fp = font2; fp - font2 < fc; ++fp) {
   1103 
   1104 		if (**fp == '-')
   1105 			pattern = XftXlfdParse(*fp, False, False);
   1106 		else
   1107 			pattern = FcNameParse((FcChar8 *)*fp);
   1108 
   1109 		if (!pattern)
   1110 			die("can't open spare font %s\n", *fp);
   1111 
   1112 		if (defaultfontsize > 0) {
   1113 			sizeshift = usedfontsize - defaultfontsize;
   1114 			if (sizeshift != 0 &&
   1115 					FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
   1116 					FcResultMatch) {
   1117 				fontval += sizeshift;
   1118 				FcPatternDel(pattern, FC_PIXEL_SIZE);
   1119 				FcPatternDel(pattern, FC_SIZE);
   1120 				FcPatternAddDouble(pattern, FC_PIXEL_SIZE, fontval);
   1121 			}
   1122 		}
   1123 
   1124 		FcPatternAddBool(pattern, FC_SCALABLE, 1);
   1125 
   1126 		FcConfigSubstitute(NULL, pattern, FcMatchPattern);
   1127 		XftDefaultSubstitute(xw.dpy, xw.scr, pattern);
   1128 
   1129 		if (xloadsparefont(pattern, FRC_NORMAL))
   1130 			die("can't open spare font %s\n", *fp);
   1131 
   1132 		FcPatternDel(pattern, FC_SLANT);
   1133 		FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
   1134 		if (xloadsparefont(pattern, FRC_ITALIC))
   1135 			die("can't open spare font %s\n", *fp);
   1136 
   1137 		FcPatternDel(pattern, FC_WEIGHT);
   1138 		FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
   1139 		if (xloadsparefont(pattern, FRC_ITALICBOLD))
   1140 			die("can't open spare font %s\n", *fp);
   1141 
   1142 		FcPatternDel(pattern, FC_SLANT);
   1143 		FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
   1144 		if (xloadsparefont(pattern, FRC_BOLD))
   1145 			die("can't open spare font %s\n", *fp);
   1146 
   1147 		FcPatternDestroy(pattern);
   1148 	}
   1149 }
   1150 
   1151 void
   1152 xunloadfont(Font *f)
   1153 {
   1154 	XftFontClose(xw.dpy, f->match);
   1155 	FcPatternDestroy(f->pattern);
   1156 	if (f->set)
   1157 		FcFontSetDestroy(f->set);
   1158 }
   1159 
   1160 void
   1161 xunloadfonts(void)
   1162 {
   1163 	/* Free the loaded fonts in the font cache.  */
   1164 	while (frclen > 0)
   1165 		XftFontClose(xw.dpy, frc[--frclen].font);
   1166 
   1167 	xunloadfont(&dc.font);
   1168 	xunloadfont(&dc.bfont);
   1169 	xunloadfont(&dc.ifont);
   1170 	xunloadfont(&dc.ibfont);
   1171 }
   1172 
   1173 int
   1174 ximopen(Display *dpy)
   1175 {
   1176 	XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
   1177 	XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
   1178 
   1179 	xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
   1180 	if (xw.ime.xim == NULL)
   1181 		return 0;
   1182 
   1183 	if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
   1184 		fprintf(stderr, "XSetIMValues: "
   1185 		                "Could not set XNDestroyCallback.\n");
   1186 
   1187 	xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
   1188 	                                      NULL);
   1189 
   1190 	if (xw.ime.xic == NULL) {
   1191 		xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
   1192 		                       XIMPreeditNothing | XIMStatusNothing,
   1193 		                       XNClientWindow, xw.win,
   1194 		                       XNDestroyCallback, &icdestroy,
   1195 		                       NULL);
   1196 	}
   1197 	if (xw.ime.xic == NULL)
   1198 		fprintf(stderr, "XCreateIC: Could not create input context.\n");
   1199 
   1200 	return 1;
   1201 }
   1202 
   1203 void
   1204 ximinstantiate(Display *dpy, XPointer client, XPointer call)
   1205 {
   1206 	if (ximopen(dpy))
   1207 		XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
   1208 		                                 ximinstantiate, NULL);
   1209 }
   1210 
   1211 void
   1212 ximdestroy(XIM xim, XPointer client, XPointer call)
   1213 {
   1214 	xw.ime.xim = NULL;
   1215 	XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
   1216 	                               ximinstantiate, NULL);
   1217 	XFree(xw.ime.spotlist);
   1218 }
   1219 
   1220 int
   1221 xicdestroy(XIC xim, XPointer client, XPointer call)
   1222 {
   1223 	xw.ime.xic = NULL;
   1224 	return 1;
   1225 }
   1226 
   1227 void
   1228 xinit(int cols, int rows)
   1229 {
   1230 	XGCValues gcvalues;
   1231 	Cursor cursor;
   1232 	Window parent;
   1233 	pid_t thispid = getpid();
   1234 	XColor xmousefg, xmousebg;
   1235 
   1236 	if (!(xw.dpy = XOpenDisplay(NULL)))
   1237 		die("can't open display\n");
   1238 	xw.scr = XDefaultScreen(xw.dpy);
   1239 	xw.vis = XDefaultVisual(xw.dpy, xw.scr);
   1240 
   1241 	/* font */
   1242 	if (!FcInit())
   1243 		die("could not init fontconfig.\n");
   1244 
   1245 	usedfont = (opt_font == NULL)? font : opt_font;
   1246 	xloadfonts(usedfont, 0);
   1247 
   1248 	/* spare fonts */
   1249 	xloadsparefonts();
   1250 
   1251 	/* colors */
   1252 	xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
   1253 	xloadcols();
   1254 
   1255 	/* adjust fixed window geometry */
   1256 	win.w = 2 * borderpx + cols * win.cw;
   1257 	win.h = 2 * borderpx + rows * win.ch;
   1258 	if (xw.gm & XNegative)
   1259 		xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
   1260 	if (xw.gm & YNegative)
   1261 		xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
   1262 
   1263 	/* Events */
   1264 	xw.attrs.background_pixel = dc.col[defaultbg].pixel;
   1265 	xw.attrs.border_pixel = dc.col[defaultbg].pixel;
   1266 	xw.attrs.bit_gravity = NorthWestGravity;
   1267 	xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
   1268 		| ExposureMask | VisibilityChangeMask | StructureNotifyMask
   1269 		| ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
   1270 	xw.attrs.colormap = xw.cmap;
   1271 
   1272 	if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
   1273 		parent = XRootWindow(xw.dpy, xw.scr);
   1274 	xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
   1275 			win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
   1276 			xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
   1277 			| CWEventMask | CWColormap, &xw.attrs);
   1278 
   1279 	memset(&gcvalues, 0, sizeof(gcvalues));
   1280 	gcvalues.graphics_exposures = False;
   1281 	dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
   1282 			&gcvalues);
   1283 	xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
   1284 			DefaultDepth(xw.dpy, xw.scr));
   1285 	XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
   1286 	XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
   1287 
   1288 	/* font spec buffer */
   1289 	xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
   1290 
   1291 	/* Xft rendering context */
   1292 	xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
   1293 
   1294 	/* input methods */
   1295 	if (!ximopen(xw.dpy)) {
   1296 		XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
   1297 	                                       ximinstantiate, NULL);
   1298 	}
   1299 
   1300 	/* white cursor, black outline */
   1301 	cursor = XCreateFontCursor(xw.dpy, mouseshape);
   1302 	XDefineCursor(xw.dpy, xw.win, cursor);
   1303 
   1304 	if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
   1305 		xmousefg.red   = 0xffff;
   1306 		xmousefg.green = 0xffff;
   1307 		xmousefg.blue  = 0xffff;
   1308 	}
   1309 
   1310 	if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
   1311 		xmousebg.red   = 0x0000;
   1312 		xmousebg.green = 0x0000;
   1313 		xmousebg.blue  = 0x0000;
   1314 	}
   1315 
   1316 	XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
   1317 
   1318 	xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
   1319 	xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
   1320 	xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
   1321 	xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
   1322 	XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
   1323 
   1324 	xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
   1325 	XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
   1326 			PropModeReplace, (uchar *)&thispid, 1);
   1327 
   1328 	win.mode = MODE_NUMLOCK;
   1329 	resettitle();
   1330 	xhints();
   1331 	XMapWindow(xw.dpy, xw.win);
   1332 	XSync(xw.dpy, False);
   1333 
   1334 	clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
   1335 	clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
   1336 	xsel.primary = NULL;
   1337 	xsel.clipboard = NULL;
   1338 	xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
   1339 	if (xsel.xtarget == None)
   1340 		xsel.xtarget = XA_STRING;
   1341 }
   1342 
   1343 int
   1344 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
   1345 {
   1346 	float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
   1347 	ushort mode, prevmode = USHRT_MAX;
   1348 	Font *font = &dc.font;
   1349 	int frcflags = FRC_NORMAL;
   1350 	float runewidth = win.cw;
   1351 	Rune rune;
   1352 	FT_UInt glyphidx;
   1353 	FcResult fcres;
   1354 	FcPattern *fcpattern, *fontpattern;
   1355 	FcFontSet *fcsets[] = { NULL };
   1356 	FcCharSet *fccharset;
   1357 	int i, f, numspecs = 0;
   1358 
   1359 	for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
   1360 		/* Fetch rune and mode for current glyph. */
   1361 		rune = glyphs[i].u;
   1362 		mode = glyphs[i].mode;
   1363 
   1364 		/* Skip dummy wide-character spacing. */
   1365 		if (mode == ATTR_WDUMMY)
   1366 			continue;
   1367 
   1368 		/* Determine font for glyph if different from previous glyph. */
   1369 		if (prevmode != mode) {
   1370 			prevmode = mode;
   1371 			font = &dc.font;
   1372 			frcflags = FRC_NORMAL;
   1373 			runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
   1374 			if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
   1375 				font = &dc.ibfont;
   1376 				frcflags = FRC_ITALICBOLD;
   1377 			} else if (mode & ATTR_ITALIC) {
   1378 				font = &dc.ifont;
   1379 				frcflags = FRC_ITALIC;
   1380 			} else if (mode & ATTR_BOLD) {
   1381 				font = &dc.bfont;
   1382 				frcflags = FRC_BOLD;
   1383 			}
   1384 			yp = winy + font->ascent;
   1385 		}
   1386 
   1387 		/* Lookup character index with default font. */
   1388 		glyphidx = XftCharIndex(xw.dpy, font->match, rune);
   1389 		if (glyphidx) {
   1390 			specs[numspecs].font = font->match;
   1391 			specs[numspecs].glyph = glyphidx;
   1392 			specs[numspecs].x = (short)xp;
   1393 			specs[numspecs].y = (short)yp;
   1394 			xp += runewidth;
   1395 			numspecs++;
   1396 			continue;
   1397 		}
   1398 
   1399 		/* Fallback on font cache, search the font cache for match. */
   1400 		for (f = 0; f < frclen; f++) {
   1401 			glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
   1402 			/* Everything correct. */
   1403 			if (glyphidx && frc[f].flags == frcflags)
   1404 				break;
   1405 			/* We got a default font for a not found glyph. */
   1406 			if (!glyphidx && frc[f].flags == frcflags
   1407 					&& frc[f].unicodep == rune) {
   1408 				break;
   1409 			}
   1410 		}
   1411 
   1412 		/* Nothing was found. Use fontconfig to find matching font. */
   1413 		if (f >= frclen) {
   1414 			if (!font->set)
   1415 				font->set = FcFontSort(0, font->pattern,
   1416 				                       1, 0, &fcres);
   1417 			fcsets[0] = font->set;
   1418 
   1419 			/*
   1420 			 * Nothing was found in the cache. Now use
   1421 			 * some dozen of Fontconfig calls to get the
   1422 			 * font for one single character.
   1423 			 *
   1424 			 * Xft and fontconfig are design failures.
   1425 			 */
   1426 			fcpattern = FcPatternDuplicate(font->pattern);
   1427 			fccharset = FcCharSetCreate();
   1428 
   1429 			FcCharSetAddChar(fccharset, rune);
   1430 			FcPatternAddCharSet(fcpattern, FC_CHARSET,
   1431 					fccharset);
   1432 			FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
   1433 
   1434 			FcConfigSubstitute(0, fcpattern,
   1435 					FcMatchPattern);
   1436 			FcDefaultSubstitute(fcpattern);
   1437 
   1438 			fontpattern = FcFontSetMatch(0, fcsets, 1,
   1439 					fcpattern, &fcres);
   1440 
   1441 			/* Allocate memory for the new cache entry. */
   1442 			if (frclen >= frccap) {
   1443 				frccap += 16;
   1444 				frc = xrealloc(frc, frccap * sizeof(Fontcache));
   1445 			}
   1446 
   1447 			frc[frclen].font = XftFontOpenPattern(xw.dpy,
   1448 					fontpattern);
   1449 			if (!frc[frclen].font)
   1450 				die("XftFontOpenPattern failed seeking fallback font: %s\n",
   1451 					strerror(errno));
   1452 			frc[frclen].flags = frcflags;
   1453 			frc[frclen].unicodep = rune;
   1454 
   1455 			glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
   1456 
   1457 			f = frclen;
   1458 			frclen++;
   1459 
   1460 			FcPatternDestroy(fcpattern);
   1461 			FcCharSetDestroy(fccharset);
   1462 		}
   1463 
   1464 		specs[numspecs].font = frc[f].font;
   1465 		specs[numspecs].glyph = glyphidx;
   1466 		specs[numspecs].x = (short)xp;
   1467 		specs[numspecs].y = (short)yp;
   1468 		xp += runewidth;
   1469 		numspecs++;
   1470 	}
   1471 
   1472 	return numspecs;
   1473 }
   1474 
   1475 void
   1476 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
   1477 {
   1478 	int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
   1479 	int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
   1480 	    width = charlen * win.cw;
   1481 	Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
   1482 	XRenderColor colfg, colbg;
   1483 	XRectangle r;
   1484 
   1485 	/* Fallback on color display for attributes not supported by the font */
   1486 	if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
   1487 		if (dc.ibfont.badslant || dc.ibfont.badweight)
   1488 			base.fg = defaultattr;
   1489 	} else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
   1490 	    (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
   1491 		base.fg = defaultattr;
   1492 	}
   1493 
   1494 	if (IS_TRUECOL(base.fg)) {
   1495 		colfg.alpha = 0xffff;
   1496 		colfg.red = TRUERED(base.fg);
   1497 		colfg.green = TRUEGREEN(base.fg);
   1498 		colfg.blue = TRUEBLUE(base.fg);
   1499 		XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
   1500 		fg = &truefg;
   1501 	} else {
   1502 		fg = &dc.col[base.fg];
   1503 	}
   1504 
   1505 	if (IS_TRUECOL(base.bg)) {
   1506 		colbg.alpha = 0xffff;
   1507 		colbg.green = TRUEGREEN(base.bg);
   1508 		colbg.red = TRUERED(base.bg);
   1509 		colbg.blue = TRUEBLUE(base.bg);
   1510 		XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
   1511 		bg = &truebg;
   1512 	} else {
   1513 		bg = &dc.col[base.bg];
   1514 	}
   1515 
   1516 	/* Change basic system colors [0-7] to bright system colors [8-15] */
   1517 	if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
   1518 		fg = &dc.col[base.fg + 8];
   1519 
   1520 	if (IS_SET(MODE_REVERSE)) {
   1521 		if (fg == &dc.col[defaultfg]) {
   1522 			fg = &dc.col[defaultbg];
   1523 		} else {
   1524 			colfg.red = ~fg->color.red;
   1525 			colfg.green = ~fg->color.green;
   1526 			colfg.blue = ~fg->color.blue;
   1527 			colfg.alpha = fg->color.alpha;
   1528 			XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
   1529 					&revfg);
   1530 			fg = &revfg;
   1531 		}
   1532 
   1533 		if (bg == &dc.col[defaultbg]) {
   1534 			bg = &dc.col[defaultfg];
   1535 		} else {
   1536 			colbg.red = ~bg->color.red;
   1537 			colbg.green = ~bg->color.green;
   1538 			colbg.blue = ~bg->color.blue;
   1539 			colbg.alpha = bg->color.alpha;
   1540 			XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
   1541 					&revbg);
   1542 			bg = &revbg;
   1543 		}
   1544 	}
   1545 
   1546 	if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
   1547 		colfg.red = fg->color.red / 2;
   1548 		colfg.green = fg->color.green / 2;
   1549 		colfg.blue = fg->color.blue / 2;
   1550 		colfg.alpha = fg->color.alpha;
   1551 		XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
   1552 		fg = &revfg;
   1553 	}
   1554 
   1555 	if (base.mode & ATTR_REVERSE) {
   1556 		temp = fg;
   1557 		fg = bg;
   1558 		bg = temp;
   1559 	}
   1560 
   1561 	if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
   1562 		fg = bg;
   1563 
   1564 	if (base.mode & ATTR_INVISIBLE)
   1565 		fg = bg;
   1566 
   1567 	/* Intelligent cleaning up of the borders. */
   1568 	if (x == 0) {
   1569 		xclear(0, (y == 0)? 0 : winy, borderpx,
   1570 			winy + win.ch +
   1571 			((winy + win.ch >= borderpx + win.th)? win.h : 0));
   1572 	}
   1573 	if (winx + width >= borderpx + win.tw) {
   1574 		xclear(winx + width, (y == 0)? 0 : winy, win.w,
   1575 			((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
   1576 	}
   1577 	if (y == 0)
   1578 		xclear(winx, 0, winx + width, borderpx);
   1579 	if (winy + win.ch >= borderpx + win.th)
   1580 		xclear(winx, winy + win.ch, winx + width, win.h);
   1581 
   1582 	/* Clean up the region we want to draw to. */
   1583 	XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
   1584 
   1585 	/* Set the clip region because Xft is sometimes dirty. */
   1586 	r.x = 0;
   1587 	r.y = 0;
   1588 	r.height = win.ch;
   1589 	r.width = width;
   1590 	XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
   1591 
   1592 	/* Render the glyphs. */
   1593 	XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
   1594 
   1595 	/* Render underline and strikethrough. */
   1596 	if (base.mode & ATTR_UNDERLINE) {
   1597 		XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent * chscale + 1,
   1598 				width, 1);
   1599 	}
   1600 
   1601 	if (base.mode & ATTR_STRUCK) {
   1602 		XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent * chscale / 3,
   1603 				width, 1);
   1604 	}
   1605 
   1606 	/* Reset clip to none. */
   1607 	XftDrawSetClip(xw.draw, 0);
   1608 }
   1609 
   1610 void
   1611 xdrawglyph(Glyph g, int x, int y)
   1612 {
   1613 	int numspecs;
   1614 	XftGlyphFontSpec spec;
   1615 
   1616 	numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
   1617 	xdrawglyphfontspecs(&spec, g, numspecs, x, y);
   1618 }
   1619 
   1620 void
   1621 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
   1622 {
   1623 	Color drawcol;
   1624 
   1625 	/* remove the old cursor */
   1626 	if (selected(ox, oy))
   1627 		og.mode ^= ATTR_REVERSE;
   1628 	xdrawglyph(og, ox, oy);
   1629 
   1630 	if (IS_SET(MODE_HIDE))
   1631 		return;
   1632 
   1633 	/*
   1634 	 * Select the right color for the right mode.
   1635 	 */
   1636 	g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
   1637 
   1638 	if (IS_SET(MODE_REVERSE)) {
   1639 		g.mode |= ATTR_REVERSE;
   1640 		g.bg = defaultfg;
   1641 		if (selected(cx, cy)) {
   1642 			drawcol = dc.col[defaultcs];
   1643 			g.fg = defaultrcs;
   1644 		} else {
   1645 			drawcol = dc.col[defaultrcs];
   1646 			g.fg = defaultcs;
   1647 		}
   1648 	} else {
   1649 		if (selected(cx, cy)) {
   1650 			g.fg = defaultfg;
   1651 			g.bg = defaultrcs;
   1652 		} else {
   1653 			g.fg = defaultbg;
   1654 			g.bg = defaultcs;
   1655 		}
   1656 		drawcol = dc.col[g.bg];
   1657 	}
   1658 
   1659 	/* draw the new one */
   1660 	if (IS_SET(MODE_FOCUSED)) {
   1661 		switch (win.cursor) {
   1662 		case 7: /* st extension */
   1663 			g.u = 0x2603; /* snowman (U+2603) */
   1664 			/* FALLTHROUGH */
   1665 		case 0: /* Blinking Block */
   1666 		case 1: /* Blinking Block (Default) */
   1667 		case 2: /* Steady Block */
   1668 			xdrawglyph(g, cx, cy);
   1669 			break;
   1670 		case 3: /* Blinking Underline */
   1671 		case 4: /* Steady Underline */
   1672 			XftDrawRect(xw.draw, &drawcol,
   1673 					borderpx + cx * win.cw,
   1674 					borderpx + (cy + 1) * win.ch - \
   1675 						cursorthickness,
   1676 					win.cw, cursorthickness);
   1677 			break;
   1678 		case 5: /* Blinking bar */
   1679 		case 6: /* Steady bar */
   1680 			XftDrawRect(xw.draw, &drawcol,
   1681 					borderpx + cx * win.cw,
   1682 					borderpx + cy * win.ch,
   1683 					cursorthickness, win.ch);
   1684 			break;
   1685 		}
   1686 	} else {
   1687 		XftDrawRect(xw.draw, &drawcol,
   1688 				borderpx + cx * win.cw,
   1689 				borderpx + cy * win.ch,
   1690 				win.cw - 1, 1);
   1691 		XftDrawRect(xw.draw, &drawcol,
   1692 				borderpx + cx * win.cw,
   1693 				borderpx + cy * win.ch,
   1694 				1, win.ch - 1);
   1695 		XftDrawRect(xw.draw, &drawcol,
   1696 				borderpx + (cx + 1) * win.cw - 1,
   1697 				borderpx + cy * win.ch,
   1698 				1, win.ch - 1);
   1699 		XftDrawRect(xw.draw, &drawcol,
   1700 				borderpx + cx * win.cw,
   1701 				borderpx + (cy + 1) * win.ch - 1,
   1702 				win.cw, 1);
   1703 	}
   1704 }
   1705 
   1706 void
   1707 xsetenv(void)
   1708 {
   1709 	char buf[sizeof(long) * 8 + 1];
   1710 
   1711 	snprintf(buf, sizeof(buf), "%lu", xw.win);
   1712 	setenv("WINDOWID", buf, 1);
   1713 }
   1714 
   1715 void
   1716 xseticontitle(char *p)
   1717 {
   1718 	XTextProperty prop;
   1719 	DEFAULT(p, opt_title);
   1720 
   1721 	if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
   1722 	                                &prop) != Success)
   1723 		return;
   1724 	XSetWMIconName(xw.dpy, xw.win, &prop);
   1725 	XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
   1726 	XFree(prop.value);
   1727 }
   1728 
   1729 void
   1730 xsettitle(char *p)
   1731 {
   1732 	XTextProperty prop;
   1733 	DEFAULT(p, opt_title);
   1734 
   1735 	if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
   1736 	                                &prop) != Success)
   1737 		return;
   1738 	XSetWMName(xw.dpy, xw.win, &prop);
   1739 	XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
   1740 	XFree(prop.value);
   1741 }
   1742 
   1743 int
   1744 xstartdraw(void)
   1745 {
   1746 	if (IS_SET(MODE_VISIBLE))
   1747 		XCopyArea(xw.dpy, xw.win, xw.buf, dc.gc, 0, 0, win.w, win.h, 0, 0);
   1748 	return IS_SET(MODE_VISIBLE);
   1749 }
   1750 
   1751 void
   1752 xdrawline(Line line, int x1, int y1, int x2)
   1753 {
   1754 	int i, x, ox, numspecs;
   1755 	Glyph base, new;
   1756 	XftGlyphFontSpec *specs = xw.specbuf;
   1757 
   1758 	numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
   1759 	i = ox = 0;
   1760 	for (x = x1; x < x2 && i < numspecs; x++) {
   1761 		new = line[x];
   1762 		if (new.mode == ATTR_WDUMMY)
   1763 			continue;
   1764 		if (selected(x, y1))
   1765 			new.mode ^= ATTR_REVERSE;
   1766 		if (i > 0 && ATTRCMP(base, new)) {
   1767 			xdrawglyphfontspecs(specs, base, i, ox, y1);
   1768 			specs += i;
   1769 			numspecs -= i;
   1770 			i = 0;
   1771 		}
   1772 		if (i == 0) {
   1773 			ox = x;
   1774 			base = new;
   1775 		}
   1776 		i++;
   1777 	}
   1778 	if (i > 0)
   1779 		xdrawglyphfontspecs(specs, base, i, ox, y1);
   1780 }
   1781 
   1782 void
   1783 xfinishdraw(void)
   1784 {
   1785 	XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
   1786 			win.h, 0, 0);
   1787 	XSetForeground(xw.dpy, dc.gc,
   1788 			dc.col[IS_SET(MODE_REVERSE)?
   1789 				defaultfg : defaultbg].pixel);
   1790 }
   1791 
   1792 void
   1793 xximspot(int x, int y)
   1794 {
   1795 	if (xw.ime.xic == NULL)
   1796 		return;
   1797 
   1798 	xw.ime.spot.x = borderpx + x * win.cw;
   1799 	xw.ime.spot.y = borderpx + (y + 1) * win.ch;
   1800 
   1801 	XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
   1802 }
   1803 
   1804 void
   1805 expose(XEvent *ev)
   1806 {
   1807 	redraw();
   1808 }
   1809 
   1810 void
   1811 visibility(XEvent *ev)
   1812 {
   1813 	XVisibilityEvent *e = &ev->xvisibility;
   1814 
   1815 	MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
   1816 }
   1817 
   1818 void
   1819 unmap(XEvent *ev)
   1820 {
   1821 	win.mode &= ~MODE_VISIBLE;
   1822 }
   1823 
   1824 void
   1825 xsetpointermotion(int set)
   1826 {
   1827 	MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
   1828 	XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
   1829 }
   1830 
   1831 void
   1832 xsetmode(int set, unsigned int flags)
   1833 {
   1834 	int mode = win.mode;
   1835 	MODBIT(win.mode, set, flags);
   1836 	if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
   1837 		redraw();
   1838 }
   1839 
   1840 int
   1841 xsetcursor(int cursor)
   1842 {
   1843 	if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
   1844 		return 1;
   1845 	win.cursor = cursor;
   1846 	return 0;
   1847 }
   1848 
   1849 void
   1850 xseturgency(int add)
   1851 {
   1852 	XWMHints *h = XGetWMHints(xw.dpy, xw.win);
   1853 
   1854 	MODBIT(h->flags, add, XUrgencyHint);
   1855 	XSetWMHints(xw.dpy, xw.win, h);
   1856 	XFree(h);
   1857 }
   1858 
   1859 void
   1860 xbell(void)
   1861 {
   1862 	if (!(IS_SET(MODE_FOCUSED)))
   1863 		xseturgency(1);
   1864 	if (bellvolume)
   1865 		XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
   1866 }
   1867 
   1868 void
   1869 focus(XEvent *ev)
   1870 {
   1871 	XFocusChangeEvent *e = &ev->xfocus;
   1872 
   1873 	if (e->mode == NotifyGrab)
   1874 		return;
   1875 
   1876 	if (ev->type == FocusIn) {
   1877 		if (xw.ime.xic)
   1878 			XSetICFocus(xw.ime.xic);
   1879 		win.mode |= MODE_FOCUSED;
   1880 		xseturgency(0);
   1881 		if (IS_SET(MODE_FOCUS))
   1882 			ttywrite("\033[I", 3, 0);
   1883 	} else {
   1884 		if (xw.ime.xic)
   1885 			XUnsetICFocus(xw.ime.xic);
   1886 		win.mode &= ~MODE_FOCUSED;
   1887 		if (IS_SET(MODE_FOCUS))
   1888 			ttywrite("\033[O", 3, 0);
   1889 	}
   1890 }
   1891 
   1892 int
   1893 match(uint mask, uint state)
   1894 {
   1895 	return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
   1896 }
   1897 
   1898 char*
   1899 kmap(KeySym k, uint state)
   1900 {
   1901 	Key *kp;
   1902 	int i;
   1903 
   1904 	/* Check for mapped keys out of X11 function keys. */
   1905 	for (i = 0; i < LEN(mappedkeys); i++) {
   1906 		if (mappedkeys[i] == k)
   1907 			break;
   1908 	}
   1909 	if (i == LEN(mappedkeys)) {
   1910 		if ((k & 0xFFFF) < 0xFD00)
   1911 			return NULL;
   1912 	}
   1913 
   1914 	for (kp = key; kp < key + LEN(key); kp++) {
   1915 		if (kp->k != k)
   1916 			continue;
   1917 
   1918 		if (!match(kp->mask, state))
   1919 			continue;
   1920 
   1921 		if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
   1922 			continue;
   1923 		if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
   1924 			continue;
   1925 
   1926 		if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
   1927 			continue;
   1928 
   1929 		return kp->s;
   1930 	}
   1931 
   1932 	return NULL;
   1933 }
   1934 
   1935 void
   1936 kpress(XEvent *ev)
   1937 {
   1938 	XKeyEvent *e = &ev->xkey;
   1939 	KeySym ksym;
   1940 	char buf[64], *customkey;
   1941 	int len;
   1942 	Rune c;
   1943 	Status status;
   1944 	Shortcut *bp;
   1945 
   1946 	if (IS_SET(MODE_KBDLOCK))
   1947 		return;
   1948 
   1949 	if (xw.ime.xic)
   1950 		len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
   1951 	else
   1952 		len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
   1953 	/* 1. shortcuts */
   1954 	for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
   1955 		if (ksym == bp->keysym && match(bp->mod, e->state)) {
   1956 			bp->func(&(bp->arg));
   1957 			return;
   1958 		}
   1959 	}
   1960 
   1961 	/* 2. custom keys from config.h */
   1962 	if ((customkey = kmap(ksym, e->state))) {
   1963 		ttywrite(customkey, strlen(customkey), 1);
   1964 		return;
   1965 	}
   1966 
   1967 	/* 3. composed string from input method */
   1968 	if (len == 0)
   1969 		return;
   1970 	if (len == 1 && e->state & Mod1Mask) {
   1971 		if (IS_SET(MODE_8BIT)) {
   1972 			if (*buf < 0177) {
   1973 				c = *buf | 0x80;
   1974 				len = utf8encode(c, buf);
   1975 			}
   1976 		} else {
   1977 			buf[1] = buf[0];
   1978 			buf[0] = '\033';
   1979 			len = 2;
   1980 		}
   1981 	}
   1982 	ttywrite(buf, len, 1);
   1983 }
   1984 
   1985 void
   1986 cmessage(XEvent *e)
   1987 {
   1988 	/*
   1989 	 * See xembed specs
   1990 	 *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
   1991 	 */
   1992 	if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
   1993 		if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
   1994 			win.mode |= MODE_FOCUSED;
   1995 			xseturgency(0);
   1996 		} else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
   1997 			win.mode &= ~MODE_FOCUSED;
   1998 		}
   1999 	} else if (e->xclient.data.l[0] == xw.wmdeletewin) {
   2000 		ttyhangup();
   2001 		exit(0);
   2002 	}
   2003 }
   2004 
   2005 void
   2006 resize(XEvent *e)
   2007 {
   2008 	if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
   2009 		return;
   2010 
   2011 	cresize(e->xconfigure.width, e->xconfigure.height);
   2012 }
   2013 
   2014 void
   2015 run(void)
   2016 {
   2017 	XEvent ev;
   2018 	int w = win.w, h = win.h;
   2019 	fd_set rfd;
   2020 	int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
   2021 	struct timespec seltv, *tv, now, lastblink, trigger;
   2022 	double timeout;
   2023 
   2024 	/* Waiting for window mapping */
   2025 	do {
   2026 		XNextEvent(xw.dpy, &ev);
   2027 		/*
   2028 		 * This XFilterEvent call is required because of XOpenIM. It
   2029 		 * does filter out the key event and some client message for
   2030 		 * the input method too.
   2031 		 */
   2032 		if (XFilterEvent(&ev, None))
   2033 			continue;
   2034 		if (ev.type == ConfigureNotify) {
   2035 			w = ev.xconfigure.width;
   2036 			h = ev.xconfigure.height;
   2037 		}
   2038 	} while (ev.type != MapNotify);
   2039 
   2040 	ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
   2041 	cresize(w, h);
   2042 
   2043 	for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
   2044 		FD_ZERO(&rfd);
   2045 		FD_SET(ttyfd, &rfd);
   2046 		FD_SET(xfd, &rfd);
   2047 
   2048 		if (XPending(xw.dpy))
   2049 			timeout = 0;  /* existing events might not set xfd */
   2050 
   2051 		seltv.tv_sec = timeout / 1E3;
   2052 		seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
   2053 		tv = timeout >= 0 ? &seltv : NULL;
   2054 
   2055 		if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
   2056 			if (errno == EINTR)
   2057 				continue;
   2058 			die("select failed: %s\n", strerror(errno));
   2059 		}
   2060 		clock_gettime(CLOCK_MONOTONIC, &now);
   2061 
   2062 		if (FD_ISSET(ttyfd, &rfd))
   2063 			ttyread();
   2064 
   2065 		xev = 0;
   2066 		while (XPending(xw.dpy)) {
   2067 			xev = 1;
   2068 			XNextEvent(xw.dpy, &ev);
   2069 			if (XFilterEvent(&ev, None))
   2070 				continue;
   2071 			if (handler[ev.type])
   2072 				(handler[ev.type])(&ev);
   2073 		}
   2074 
   2075 		/*
   2076 		 * To reduce flicker and tearing, when new content or event
   2077 		 * triggers drawing, we first wait a bit to ensure we got
   2078 		 * everything, and if nothing new arrives - we draw.
   2079 		 * We start with trying to wait minlatency ms. If more content
   2080 		 * arrives sooner, we retry with shorter and shorter periods,
   2081 		 * and eventually draw even without idle after maxlatency ms.
   2082 		 * Typically this results in low latency while interacting,
   2083 		 * maximum latency intervals during `cat huge.txt`, and perfect
   2084 		 * sync with periodic updates from animations/key-repeats/etc.
   2085 		 */
   2086 		if (FD_ISSET(ttyfd, &rfd) || xev) {
   2087 			if (!drawing) {
   2088 				trigger = now;
   2089 				drawing = 1;
   2090 			}
   2091 			timeout = (maxlatency - TIMEDIFF(now, trigger)) \
   2092 			          / maxlatency * minlatency;
   2093 			if (timeout > 0)
   2094 				continue;  /* we have time, try to find idle */
   2095 		}
   2096 
   2097 		/* idle detected or maxlatency exhausted -> draw */
   2098 		timeout = -1;
   2099 		if (blinktimeout && tattrset(ATTR_BLINK)) {
   2100 			timeout = blinktimeout - TIMEDIFF(now, lastblink);
   2101 			if (timeout <= 0) {
   2102 				if (-timeout > blinktimeout) /* start visible */
   2103 					win.mode |= MODE_BLINK;
   2104 				win.mode ^= MODE_BLINK;
   2105 				tsetdirtattr(ATTR_BLINK);
   2106 				lastblink = now;
   2107 				timeout = blinktimeout;
   2108 			}
   2109 		}
   2110 
   2111 		draw();
   2112 		XFlush(xw.dpy);
   2113 		drawing = 0;
   2114 	}
   2115 }
   2116 
   2117 void
   2118 usage(void)
   2119 {
   2120 	die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
   2121 	    " [-n name] [-o file]\n"
   2122 	    "          [-T title] [-t title] [-w windowid]"
   2123 	    " [[-e] command [args ...]]\n"
   2124 	    "       %s [-aiv] [-c class] [-f font] [-g geometry]"
   2125 	    " [-n name] [-o file]\n"
   2126 	    "          [-T title] [-t title] [-w windowid] -l line"
   2127 	    " [stty_args ...]\n", argv0, argv0);
   2128 }
   2129 
   2130 int
   2131 main(int argc, char *argv[])
   2132 {
   2133 	xw.l = xw.t = 0;
   2134 	xw.isfixed = False;
   2135 	xsetcursor(cursorshape);
   2136 
   2137 	ARGBEGIN {
   2138 	case 'a':
   2139 		allowaltscreen = 0;
   2140 		break;
   2141 	case 'c':
   2142 		opt_class = EARGF(usage());
   2143 		break;
   2144 	case 'e':
   2145 		if (argc > 0)
   2146 			--argc, ++argv;
   2147 		goto run;
   2148 	case 'f':
   2149 		opt_font = EARGF(usage());
   2150 		break;
   2151 	case 'g':
   2152 		xw.gm = XParseGeometry(EARGF(usage()),
   2153 				&xw.l, &xw.t, &cols, &rows);
   2154 		break;
   2155 	case 'i':
   2156 		xw.isfixed = 1;
   2157 		break;
   2158 	case 'o':
   2159 		opt_io = EARGF(usage());
   2160 		break;
   2161 	case 'l':
   2162 		opt_line = EARGF(usage());
   2163 		break;
   2164 	case 'n':
   2165 		opt_name = EARGF(usage());
   2166 		break;
   2167 	case 't':
   2168 	case 'T':
   2169 		opt_title = EARGF(usage());
   2170 		break;
   2171 	case 'w':
   2172 		opt_embed = EARGF(usage());
   2173 		break;
   2174 	case 'v':
   2175 		die("%s " VERSION "\n", argv0);
   2176 		break;
   2177 	default:
   2178 		usage();
   2179 	} ARGEND;
   2180 
   2181 run:
   2182 	if (argc > 0) /* eat all remaining arguments */
   2183 		opt_cmd = argv;
   2184 
   2185 	if (!opt_title)
   2186 		opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
   2187 
   2188 	setlocale(LC_CTYPE, "");
   2189 	XSetLocaleModifiers("");
   2190 	cols = MAX(cols, 1);
   2191 	rows = MAX(rows, 1);
   2192 	tnew(cols, rows);
   2193 	xinit(cols, rows);
   2194 	xsetenv();
   2195 	selinit();
   2196 	run();
   2197 
   2198 	return 0;
   2199 }