# st

Unnamed repository; edit this file 'description' to name the repository.

| Log | Files | Refs | README | LICENSE

x.c (49185B)

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