st-noxz

[fork] suckless st - personal fork
git clone git://git.noxz.tech/st-noxz
Log | Files | Refs | README | LICENSE

x.c (48779B)


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