st

simple terminal
git clone git://git.suckless.org/st
Log | Files | Refs | README | LICENSE

x.c (47421B)


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