nixos-dotfiles

nixos-dotfiles

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