st

Patched version of https://st.suckless.org/
git clone https://git.inz.fi/st/
Log | Files | Refs | README | LICENSE

x.c (49053B)


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