st

Simple Terminal from suckless utilities
git clone git://git.thepablogq.xyz/st
Log | Files | Refs | README | LICENSE

x.c (47742B)


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