st

my build of st
git clone git://git.hanetzok.net/st
Log | Files | Refs | README | LICENSE

x.c (49072B)


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