st

[fork] terminal
git clone https://hhvn.uk/st
git clone git://hhvn.uk/st
Log | Files | Refs | README | LICENSE

x.c (47300B)


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