st-noxz

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

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