st

My custom build of st terminal.
git clone https://git.mtkn.jp/st
Log | Files | Refs | README | LICENSE

x.c (51783B)


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