st

my build of st - simple terminal
git clone git://git.kocotian.pl/st.git
Log | Files | Refs | README | LICENSE

x.c (49073B)


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