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