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