st

my build of st
git clone git://giovanniamaral.com/st
Log | Files | Refs | README | LICENSE

x.c (49808B)


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