]> Sergey Matveev's repositories - st.git/blob - x.c
bump version to 0.8.5
[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|1<<14)
52
53 /* function definitions used in config.h */
54 static void clipcopy(const Arg *);
55 static void clippaste(const Arg *);
56 static void numlock(const Arg *);
57 static void selpaste(const Arg *);
58 static void zoom(const Arg *);
59 static void zoomabs(const Arg *);
60 static void zoomreset(const Arg *);
61 static void ttysend(const Arg *);
62
63 /* config.h for applying patches and the configuration. */
64 #include "config.h"
65
66 /* XEMBED messages */
67 #define XEMBED_FOCUS_IN  4
68 #define XEMBED_FOCUS_OUT 5
69
70 /* macros */
71 #define IS_SET(flag)            ((win.mode & (flag)) != 0)
72 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
73 #define TRUEGREEN(x)            (((x) & 0xff00))
74 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
75
76 typedef XftDraw *Draw;
77 typedef XftColor Color;
78 typedef XftGlyphFontSpec GlyphFontSpec;
79
80 /* Purely graphic info */
81 typedef struct {
82         int tw, th; /* tty width and height */
83         int w, h; /* window width and height */
84         int 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(const 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 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
804 {
805         if (!BETWEEN(x, 0, dc.collen))
806                 return 1;
807
808         *r = dc.col[x].color.red >> 8;
809         *g = dc.col[x].color.green >> 8;
810         *b = dc.col[x].color.blue >> 8;
811
812         return 0;
813 }
814
815 int
816 xsetcolorname(int x, const char *name)
817 {
818         Color ncolor;
819
820         if (!BETWEEN(x, 0, dc.collen))
821                 return 1;
822
823         if (!xloadcolor(x, name, &ncolor))
824                 return 1;
825
826         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
827         dc.col[x] = ncolor;
828
829         return 0;
830 }
831
832 /*
833  * Absolute coordinates.
834  */
835 void
836 xclear(int x1, int y1, int x2, int y2)
837 {
838         XftDrawRect(xw.draw,
839                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
840                         x1, y1, x2-x1, y2-y1);
841 }
842
843 void
844 xhints(void)
845 {
846         XClassHint class = {opt_name ? opt_name : termname,
847                             opt_class ? opt_class : termname};
848         XWMHints wm = {.flags = InputHint, .input = 1};
849         XSizeHints *sizeh;
850
851         sizeh = XAllocSizeHints();
852
853         sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
854         sizeh->height = win.h;
855         sizeh->width = win.w;
856         sizeh->height_inc = win.ch;
857         sizeh->width_inc = win.cw;
858         sizeh->base_height = 2 * borderpx;
859         sizeh->base_width = 2 * borderpx;
860         sizeh->min_height = win.ch + 2 * borderpx;
861         sizeh->min_width = win.cw + 2 * borderpx;
862         if (xw.isfixed) {
863                 sizeh->flags |= PMaxSize;
864                 sizeh->min_width = sizeh->max_width = win.w;
865                 sizeh->min_height = sizeh->max_height = win.h;
866         }
867         if (xw.gm & (XValue|YValue)) {
868                 sizeh->flags |= USPosition | PWinGravity;
869                 sizeh->x = xw.l;
870                 sizeh->y = xw.t;
871                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
872         }
873
874         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
875                         &class);
876         XFree(sizeh);
877 }
878
879 int
880 xgeommasktogravity(int mask)
881 {
882         switch (mask & (XNegative|YNegative)) {
883         case 0:
884                 return NorthWestGravity;
885         case XNegative:
886                 return NorthEastGravity;
887         case YNegative:
888                 return SouthWestGravity;
889         }
890
891         return SouthEastGravity;
892 }
893
894 int
895 xloadfont(Font *f, FcPattern *pattern)
896 {
897         FcPattern *configured;
898         FcPattern *match;
899         FcResult result;
900         XGlyphInfo extents;
901         int wantattr, haveattr;
902
903         /*
904          * Manually configure instead of calling XftMatchFont
905          * so that we can use the configured pattern for
906          * "missing glyph" lookups.
907          */
908         configured = FcPatternDuplicate(pattern);
909         if (!configured)
910                 return 1;
911
912         FcConfigSubstitute(NULL, configured, FcMatchPattern);
913         XftDefaultSubstitute(xw.dpy, xw.scr, configured);
914
915         match = FcFontMatch(NULL, configured, &result);
916         if (!match) {
917                 FcPatternDestroy(configured);
918                 return 1;
919         }
920
921         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
922                 FcPatternDestroy(configured);
923                 FcPatternDestroy(match);
924                 return 1;
925         }
926
927         if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
928             XftResultMatch)) {
929                 /*
930                  * Check if xft was unable to find a font with the appropriate
931                  * slant but gave us one anyway. Try to mitigate.
932                  */
933                 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
934                     &haveattr) != XftResultMatch) || haveattr < wantattr) {
935                         f->badslant = 1;
936                         fputs("font slant does not match\n", stderr);
937                 }
938         }
939
940         if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
941             XftResultMatch)) {
942                 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
943                     &haveattr) != XftResultMatch) || haveattr != wantattr) {
944                         f->badweight = 1;
945                         fputs("font weight does not match\n", stderr);
946                 }
947         }
948
949         XftTextExtentsUtf8(xw.dpy, f->match,
950                 (const FcChar8 *) ascii_printable,
951                 strlen(ascii_printable), &extents);
952
953         f->set = NULL;
954         f->pattern = configured;
955
956         f->ascent = f->match->ascent;
957         f->descent = f->match->descent;
958         f->lbearing = 0;
959         f->rbearing = f->match->max_advance_width;
960
961         f->height = f->ascent + f->descent;
962         f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
963
964         return 0;
965 }
966
967 void
968 xloadfonts(const char *fontstr, double fontsize)
969 {
970         FcPattern *pattern;
971         double fontval;
972
973         if (fontstr[0] == '-')
974                 pattern = XftXlfdParse(fontstr, False, False);
975         else
976                 pattern = FcNameParse((const FcChar8 *)fontstr);
977
978         if (!pattern)
979                 die("can't open font %s\n", fontstr);
980
981         if (fontsize > 1) {
982                 FcPatternDel(pattern, FC_PIXEL_SIZE);
983                 FcPatternDel(pattern, FC_SIZE);
984                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
985                 usedfontsize = fontsize;
986         } else {
987                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
988                                 FcResultMatch) {
989                         usedfontsize = fontval;
990                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
991                                 FcResultMatch) {
992                         usedfontsize = -1;
993                 } else {
994                         /*
995                          * Default font size is 12, if none given. This is to
996                          * have a known usedfontsize value.
997                          */
998                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
999                         usedfontsize = 12;
1000                 }
1001                 defaultfontsize = usedfontsize;
1002         }
1003
1004         if (xloadfont(&dc.font, pattern))
1005                 die("can't open font %s\n", fontstr);
1006
1007         if (usedfontsize < 0) {
1008                 FcPatternGetDouble(dc.font.match->pattern,
1009                                    FC_PIXEL_SIZE, 0, &fontval);
1010                 usedfontsize = fontval;
1011                 if (fontsize == 0)
1012                         defaultfontsize = fontval;
1013         }
1014
1015         /* Setting character width and height. */
1016         win.cw = ceilf(dc.font.width * cwscale);
1017         win.ch = ceilf(dc.font.height * chscale);
1018
1019         FcPatternDel(pattern, FC_SLANT);
1020         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1021         if (xloadfont(&dc.ifont, pattern))
1022                 die("can't open font %s\n", fontstr);
1023
1024         FcPatternDel(pattern, FC_WEIGHT);
1025         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1026         if (xloadfont(&dc.ibfont, pattern))
1027                 die("can't open font %s\n", fontstr);
1028
1029         FcPatternDel(pattern, FC_SLANT);
1030         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1031         if (xloadfont(&dc.bfont, pattern))
1032                 die("can't open font %s\n", fontstr);
1033
1034         FcPatternDestroy(pattern);
1035 }
1036
1037 void
1038 xunloadfont(Font *f)
1039 {
1040         XftFontClose(xw.dpy, f->match);
1041         FcPatternDestroy(f->pattern);
1042         if (f->set)
1043                 FcFontSetDestroy(f->set);
1044 }
1045
1046 void
1047 xunloadfonts(void)
1048 {
1049         /* Free the loaded fonts in the font cache.  */
1050         while (frclen > 0)
1051                 XftFontClose(xw.dpy, frc[--frclen].font);
1052
1053         xunloadfont(&dc.font);
1054         xunloadfont(&dc.bfont);
1055         xunloadfont(&dc.ifont);
1056         xunloadfont(&dc.ibfont);
1057 }
1058
1059 int
1060 ximopen(Display *dpy)
1061 {
1062         XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1063         XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1064
1065         xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1066         if (xw.ime.xim == NULL)
1067                 return 0;
1068
1069         if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1070                 fprintf(stderr, "XSetIMValues: "
1071                                 "Could not set XNDestroyCallback.\n");
1072
1073         xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1074                                               NULL);
1075
1076         if (xw.ime.xic == NULL) {
1077                 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1078                                        XIMPreeditNothing | XIMStatusNothing,
1079                                        XNClientWindow, xw.win,
1080                                        XNDestroyCallback, &icdestroy,
1081                                        NULL);
1082         }
1083         if (xw.ime.xic == NULL)
1084                 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1085
1086         return 1;
1087 }
1088
1089 void
1090 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1091 {
1092         if (ximopen(dpy))
1093                 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1094                                                  ximinstantiate, NULL);
1095 }
1096
1097 void
1098 ximdestroy(XIM xim, XPointer client, XPointer call)
1099 {
1100         xw.ime.xim = NULL;
1101         XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1102                                        ximinstantiate, NULL);
1103         XFree(xw.ime.spotlist);
1104 }
1105
1106 int
1107 xicdestroy(XIC xim, XPointer client, XPointer call)
1108 {
1109         xw.ime.xic = NULL;
1110         return 1;
1111 }
1112
1113 void
1114 xinit(int cols, int rows)
1115 {
1116         XGCValues gcvalues;
1117         Cursor cursor;
1118         Window parent;
1119         pid_t thispid = getpid();
1120         XColor xmousefg, xmousebg;
1121
1122         if (!(xw.dpy = XOpenDisplay(NULL)))
1123                 die("can't open display\n");
1124         xw.scr = XDefaultScreen(xw.dpy);
1125         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1126
1127         /* font */
1128         if (!FcInit())
1129                 die("could not init fontconfig.\n");
1130
1131         usedfont = (opt_font == NULL)? font : opt_font;
1132         xloadfonts(usedfont, 0);
1133
1134         /* colors */
1135         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1136         xloadcols();
1137
1138         /* adjust fixed window geometry */
1139         win.w = 2 * borderpx + cols * win.cw;
1140         win.h = 2 * borderpx + rows * win.ch;
1141         if (xw.gm & XNegative)
1142                 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1143         if (xw.gm & YNegative)
1144                 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1145
1146         /* Events */
1147         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1148         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1149         xw.attrs.bit_gravity = NorthWestGravity;
1150         xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1151                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1152                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1153         xw.attrs.colormap = xw.cmap;
1154
1155         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1156                 parent = XRootWindow(xw.dpy, xw.scr);
1157         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1158                         win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1159                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1160                         | CWEventMask | CWColormap, &xw.attrs);
1161
1162         memset(&gcvalues, 0, sizeof(gcvalues));
1163         gcvalues.graphics_exposures = False;
1164         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1165                         &gcvalues);
1166         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1167                         DefaultDepth(xw.dpy, xw.scr));
1168         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1169         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1170
1171         /* font spec buffer */
1172         xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1173
1174         /* Xft rendering context */
1175         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1176
1177         /* input methods */
1178         if (!ximopen(xw.dpy)) {
1179                 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1180                                                ximinstantiate, NULL);
1181         }
1182
1183         /* white cursor, black outline */
1184         cursor = XCreateFontCursor(xw.dpy, mouseshape);
1185         XDefineCursor(xw.dpy, xw.win, cursor);
1186
1187         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1188                 xmousefg.red   = 0xffff;
1189                 xmousefg.green = 0xffff;
1190                 xmousefg.blue  = 0xffff;
1191         }
1192
1193         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1194                 xmousebg.red   = 0x0000;
1195                 xmousebg.green = 0x0000;
1196                 xmousebg.blue  = 0x0000;
1197         }
1198
1199         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1200
1201         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1202         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1203         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1204         xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1205         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1206
1207         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1208         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1209                         PropModeReplace, (uchar *)&thispid, 1);
1210
1211         win.mode = MODE_NUMLOCK;
1212         resettitle();
1213         xhints();
1214         XMapWindow(xw.dpy, xw.win);
1215         XSync(xw.dpy, False);
1216
1217         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1218         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1219         xsel.primary = NULL;
1220         xsel.clipboard = NULL;
1221         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1222         if (xsel.xtarget == None)
1223                 xsel.xtarget = XA_STRING;
1224 }
1225
1226 int
1227 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1228 {
1229         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1230         ushort mode, prevmode = USHRT_MAX;
1231         Font *font = &dc.font;
1232         int frcflags = FRC_NORMAL;
1233         float runewidth = win.cw;
1234         Rune rune;
1235         FT_UInt glyphidx;
1236         FcResult fcres;
1237         FcPattern *fcpattern, *fontpattern;
1238         FcFontSet *fcsets[] = { NULL };
1239         FcCharSet *fccharset;
1240         int i, f, numspecs = 0;
1241
1242         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1243                 /* Fetch rune and mode for current glyph. */
1244                 rune = glyphs[i].u;
1245                 mode = glyphs[i].mode;
1246
1247                 /* Skip dummy wide-character spacing. */
1248                 if (mode == ATTR_WDUMMY)
1249                         continue;
1250
1251                 /* Determine font for glyph if different from previous glyph. */
1252                 if (prevmode != mode) {
1253                         prevmode = mode;
1254                         font = &dc.font;
1255                         frcflags = FRC_NORMAL;
1256                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1257                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1258                                 font = &dc.ibfont;
1259                                 frcflags = FRC_ITALICBOLD;
1260                         } else if (mode & ATTR_ITALIC) {
1261                                 font = &dc.ifont;
1262                                 frcflags = FRC_ITALIC;
1263                         } else if (mode & ATTR_BOLD) {
1264                                 font = &dc.bfont;
1265                                 frcflags = FRC_BOLD;
1266                         }
1267                         yp = winy + font->ascent;
1268                 }
1269
1270                 /* Lookup character index with default font. */
1271                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1272                 if (glyphidx) {
1273                         specs[numspecs].font = font->match;
1274                         specs[numspecs].glyph = glyphidx;
1275                         specs[numspecs].x = (short)xp;
1276                         specs[numspecs].y = (short)yp;
1277                         xp += runewidth;
1278                         numspecs++;
1279                         continue;
1280                 }
1281
1282                 /* Fallback on font cache, search the font cache for match. */
1283                 for (f = 0; f < frclen; f++) {
1284                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1285                         /* Everything correct. */
1286                         if (glyphidx && frc[f].flags == frcflags)
1287                                 break;
1288                         /* We got a default font for a not found glyph. */
1289                         if (!glyphidx && frc[f].flags == frcflags
1290                                         && frc[f].unicodep == rune) {
1291                                 break;
1292                         }
1293                 }
1294
1295                 /* Nothing was found. Use fontconfig to find matching font. */
1296                 if (f >= frclen) {
1297                         if (!font->set)
1298                                 font->set = FcFontSort(0, font->pattern,
1299                                                        1, 0, &fcres);
1300                         fcsets[0] = font->set;
1301
1302                         /*
1303                          * Nothing was found in the cache. Now use
1304                          * some dozen of Fontconfig calls to get the
1305                          * font for one single character.
1306                          *
1307                          * Xft and fontconfig are design failures.
1308                          */
1309                         fcpattern = FcPatternDuplicate(font->pattern);
1310                         fccharset = FcCharSetCreate();
1311
1312                         FcCharSetAddChar(fccharset, rune);
1313                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1314                                         fccharset);
1315                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1316
1317                         FcConfigSubstitute(0, fcpattern,
1318                                         FcMatchPattern);
1319                         FcDefaultSubstitute(fcpattern);
1320
1321                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1322                                         fcpattern, &fcres);
1323
1324                         /* Allocate memory for the new cache entry. */
1325                         if (frclen >= frccap) {
1326                                 frccap += 16;
1327                                 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1328                         }
1329
1330                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1331                                         fontpattern);
1332                         if (!frc[frclen].font)
1333                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1334                                         strerror(errno));
1335                         frc[frclen].flags = frcflags;
1336                         frc[frclen].unicodep = rune;
1337
1338                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1339
1340                         f = frclen;
1341                         frclen++;
1342
1343                         FcPatternDestroy(fcpattern);
1344                         FcCharSetDestroy(fccharset);
1345                 }
1346
1347                 specs[numspecs].font = frc[f].font;
1348                 specs[numspecs].glyph = glyphidx;
1349                 specs[numspecs].x = (short)xp;
1350                 specs[numspecs].y = (short)yp;
1351                 xp += runewidth;
1352                 numspecs++;
1353         }
1354
1355         return numspecs;
1356 }
1357
1358 void
1359 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1360 {
1361         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1362         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1363             width = charlen * win.cw;
1364         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1365         XRenderColor colfg, colbg;
1366         XRectangle r;
1367
1368         /* Fallback on color display for attributes not supported by the font */
1369         if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1370                 if (dc.ibfont.badslant || dc.ibfont.badweight)
1371                         base.fg = defaultattr;
1372         } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1373             (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1374                 base.fg = defaultattr;
1375         }
1376
1377         if (IS_TRUECOL(base.fg)) {
1378                 colfg.alpha = 0xffff;
1379                 colfg.red = TRUERED(base.fg);
1380                 colfg.green = TRUEGREEN(base.fg);
1381                 colfg.blue = TRUEBLUE(base.fg);
1382                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1383                 fg = &truefg;
1384         } else {
1385                 fg = &dc.col[base.fg];
1386         }
1387
1388         if (IS_TRUECOL(base.bg)) {
1389                 colbg.alpha = 0xffff;
1390                 colbg.green = TRUEGREEN(base.bg);
1391                 colbg.red = TRUERED(base.bg);
1392                 colbg.blue = TRUEBLUE(base.bg);
1393                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1394                 bg = &truebg;
1395         } else {
1396                 bg = &dc.col[base.bg];
1397         }
1398
1399         /* Change basic system colors [0-7] to bright system colors [8-15] */
1400         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1401                 fg = &dc.col[base.fg + 8];
1402
1403         if (IS_SET(MODE_REVERSE)) {
1404                 if (fg == &dc.col[defaultfg]) {
1405                         fg = &dc.col[defaultbg];
1406                 } else {
1407                         colfg.red = ~fg->color.red;
1408                         colfg.green = ~fg->color.green;
1409                         colfg.blue = ~fg->color.blue;
1410                         colfg.alpha = fg->color.alpha;
1411                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1412                                         &revfg);
1413                         fg = &revfg;
1414                 }
1415
1416                 if (bg == &dc.col[defaultbg]) {
1417                         bg = &dc.col[defaultfg];
1418                 } else {
1419                         colbg.red = ~bg->color.red;
1420                         colbg.green = ~bg->color.green;
1421                         colbg.blue = ~bg->color.blue;
1422                         colbg.alpha = bg->color.alpha;
1423                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1424                                         &revbg);
1425                         bg = &revbg;
1426                 }
1427         }
1428
1429         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1430                 colfg.red = fg->color.red / 2;
1431                 colfg.green = fg->color.green / 2;
1432                 colfg.blue = fg->color.blue / 2;
1433                 colfg.alpha = fg->color.alpha;
1434                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1435                 fg = &revfg;
1436         }
1437
1438         if (base.mode & ATTR_REVERSE) {
1439                 temp = fg;
1440                 fg = bg;
1441                 bg = temp;
1442         }
1443
1444         if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1445                 fg = bg;
1446
1447         if (base.mode & ATTR_INVISIBLE)
1448                 fg = bg;
1449
1450         /* Intelligent cleaning up of the borders. */
1451         if (x == 0) {
1452                 xclear(0, (y == 0)? 0 : winy, borderpx,
1453                         winy + win.ch +
1454                         ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1455         }
1456         if (winx + width >= borderpx + win.tw) {
1457                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1458                         ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1459         }
1460         if (y == 0)
1461                 xclear(winx, 0, winx + width, borderpx);
1462         if (winy + win.ch >= borderpx + win.th)
1463                 xclear(winx, winy + win.ch, winx + width, win.h);
1464
1465         /* Clean up the region we want to draw to. */
1466         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1467
1468         /* Set the clip region because Xft is sometimes dirty. */
1469         r.x = 0;
1470         r.y = 0;
1471         r.height = win.ch;
1472         r.width = width;
1473         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1474
1475         /* Render the glyphs. */
1476         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1477
1478         /* Render underline and strikethrough. */
1479         if (base.mode & ATTR_UNDERLINE) {
1480                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1481                                 width, 1);
1482         }
1483
1484         if (base.mode & ATTR_STRUCK) {
1485                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1486                                 width, 1);
1487         }
1488
1489         /* Reset clip to none. */
1490         XftDrawSetClip(xw.draw, 0);
1491 }
1492
1493 void
1494 xdrawglyph(Glyph g, int x, int y)
1495 {
1496         int numspecs;
1497         XftGlyphFontSpec spec;
1498
1499         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1500         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1501 }
1502
1503 void
1504 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1505 {
1506         Color drawcol;
1507
1508         /* remove the old cursor */
1509         if (selected(ox, oy))
1510                 og.mode ^= ATTR_REVERSE;
1511         xdrawglyph(og, ox, oy);
1512
1513         if (IS_SET(MODE_HIDE))
1514                 return;
1515
1516         /*
1517          * Select the right color for the right mode.
1518          */
1519         g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1520
1521         if (IS_SET(MODE_REVERSE)) {
1522                 g.mode |= ATTR_REVERSE;
1523                 g.bg = defaultfg;
1524                 if (selected(cx, cy)) {
1525                         drawcol = dc.col[defaultcs];
1526                         g.fg = defaultrcs;
1527                 } else {
1528                         drawcol = dc.col[defaultrcs];
1529                         g.fg = defaultcs;
1530                 }
1531         } else {
1532                 if (selected(cx, cy)) {
1533                         g.fg = defaultfg;
1534                         g.bg = defaultrcs;
1535                 } else {
1536                         g.fg = defaultbg;
1537                         g.bg = defaultcs;
1538                 }
1539                 drawcol = dc.col[g.bg];
1540         }
1541
1542         /* draw the new one */
1543         if (IS_SET(MODE_FOCUSED)) {
1544                 switch (win.cursor) {
1545                 case 7: /* st extension */
1546                         g.u = 0x2603; /* snowman (U+2603) */
1547                         /* FALLTHROUGH */
1548                 case 0: /* Blinking Block */
1549                 case 1: /* Blinking Block (Default) */
1550                 case 2: /* Steady Block */
1551                         xdrawglyph(g, cx, cy);
1552                         break;
1553                 case 3: /* Blinking Underline */
1554                 case 4: /* Steady Underline */
1555                         XftDrawRect(xw.draw, &drawcol,
1556                                         borderpx + cx * win.cw,
1557                                         borderpx + (cy + 1) * win.ch - \
1558                                                 cursorthickness,
1559                                         win.cw, cursorthickness);
1560                         break;
1561                 case 5: /* Blinking bar */
1562                 case 6: /* Steady bar */
1563                         XftDrawRect(xw.draw, &drawcol,
1564                                         borderpx + cx * win.cw,
1565                                         borderpx + cy * win.ch,
1566                                         cursorthickness, win.ch);
1567                         break;
1568                 }
1569         } else {
1570                 XftDrawRect(xw.draw, &drawcol,
1571                                 borderpx + cx * win.cw,
1572                                 borderpx + cy * win.ch,
1573                                 win.cw - 1, 1);
1574                 XftDrawRect(xw.draw, &drawcol,
1575                                 borderpx + cx * win.cw,
1576                                 borderpx + cy * win.ch,
1577                                 1, win.ch - 1);
1578                 XftDrawRect(xw.draw, &drawcol,
1579                                 borderpx + (cx + 1) * win.cw - 1,
1580                                 borderpx + cy * win.ch,
1581                                 1, win.ch - 1);
1582                 XftDrawRect(xw.draw, &drawcol,
1583                                 borderpx + cx * win.cw,
1584                                 borderpx + (cy + 1) * win.ch - 1,
1585                                 win.cw, 1);
1586         }
1587 }
1588
1589 void
1590 xsetenv(void)
1591 {
1592         char buf[sizeof(long) * 8 + 1];
1593
1594         snprintf(buf, sizeof(buf), "%lu", xw.win);
1595         setenv("WINDOWID", buf, 1);
1596 }
1597
1598 void
1599 xseticontitle(char *p)
1600 {
1601         XTextProperty prop;
1602         DEFAULT(p, opt_title);
1603
1604         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1605                                         &prop) != Success)
1606                 return;
1607         XSetWMIconName(xw.dpy, xw.win, &prop);
1608         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1609         XFree(prop.value);
1610 }
1611
1612 void
1613 xsettitle(char *p)
1614 {
1615         XTextProperty prop;
1616         DEFAULT(p, opt_title);
1617
1618         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1619                                         &prop) != Success)
1620                 return;
1621         XSetWMName(xw.dpy, xw.win, &prop);
1622         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1623         XFree(prop.value);
1624 }
1625
1626 int
1627 xstartdraw(void)
1628 {
1629         return IS_SET(MODE_VISIBLE);
1630 }
1631
1632 void
1633 xdrawline(Line line, int x1, int y1, int x2)
1634 {
1635         int i, x, ox, numspecs;
1636         Glyph base, new;
1637         XftGlyphFontSpec *specs = xw.specbuf;
1638
1639         numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1640         i = ox = 0;
1641         for (x = x1; x < x2 && i < numspecs; x++) {
1642                 new = line[x];
1643                 if (new.mode == ATTR_WDUMMY)
1644                         continue;
1645                 if (selected(x, y1))
1646                         new.mode ^= ATTR_REVERSE;
1647                 if (i > 0 && ATTRCMP(base, new)) {
1648                         xdrawglyphfontspecs(specs, base, i, ox, y1);
1649                         specs += i;
1650                         numspecs -= i;
1651                         i = 0;
1652                 }
1653                 if (i == 0) {
1654                         ox = x;
1655                         base = new;
1656                 }
1657                 i++;
1658         }
1659         if (i > 0)
1660                 xdrawglyphfontspecs(specs, base, i, ox, y1);
1661 }
1662
1663 void
1664 xfinishdraw(void)
1665 {
1666         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1667                         win.h, 0, 0);
1668         XSetForeground(xw.dpy, dc.gc,
1669                         dc.col[IS_SET(MODE_REVERSE)?
1670                                 defaultfg : defaultbg].pixel);
1671 }
1672
1673 void
1674 xximspot(int x, int y)
1675 {
1676         if (xw.ime.xic == NULL)
1677                 return;
1678
1679         xw.ime.spot.x = borderpx + x * win.cw;
1680         xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1681
1682         XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1683 }
1684
1685 void
1686 expose(XEvent *ev)
1687 {
1688         redraw();
1689 }
1690
1691 void
1692 visibility(XEvent *ev)
1693 {
1694         XVisibilityEvent *e = &ev->xvisibility;
1695
1696         MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1697 }
1698
1699 void
1700 unmap(XEvent *ev)
1701 {
1702         win.mode &= ~MODE_VISIBLE;
1703 }
1704
1705 void
1706 xsetpointermotion(int set)
1707 {
1708         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1709         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1710 }
1711
1712 void
1713 xsetmode(int set, unsigned int flags)
1714 {
1715         int mode = win.mode;
1716         MODBIT(win.mode, set, flags);
1717         if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1718                 redraw();
1719 }
1720
1721 int
1722 xsetcursor(int cursor)
1723 {
1724         if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
1725                 return 1;
1726         win.cursor = cursor;
1727         return 0;
1728 }
1729
1730 void
1731 xseturgency(int add)
1732 {
1733         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1734
1735         MODBIT(h->flags, add, XUrgencyHint);
1736         XSetWMHints(xw.dpy, xw.win, h);
1737         XFree(h);
1738 }
1739
1740 void
1741 xbell(void)
1742 {
1743         if (!(IS_SET(MODE_FOCUSED)))
1744                 xseturgency(1);
1745         if (bellvolume)
1746                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1747 }
1748
1749 void
1750 focus(XEvent *ev)
1751 {
1752         XFocusChangeEvent *e = &ev->xfocus;
1753
1754         if (e->mode == NotifyGrab)
1755                 return;
1756
1757         if (ev->type == FocusIn) {
1758                 if (xw.ime.xic)
1759                         XSetICFocus(xw.ime.xic);
1760                 win.mode |= MODE_FOCUSED;
1761                 xseturgency(0);
1762                 if (IS_SET(MODE_FOCUS))
1763                         ttywrite("\033[I", 3, 0);
1764         } else {
1765                 if (xw.ime.xic)
1766                         XUnsetICFocus(xw.ime.xic);
1767                 win.mode &= ~MODE_FOCUSED;
1768                 if (IS_SET(MODE_FOCUS))
1769                         ttywrite("\033[O", 3, 0);
1770         }
1771 }
1772
1773 int
1774 match(uint mask, uint state)
1775 {
1776         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1777 }
1778
1779 char*
1780 kmap(KeySym k, uint state)
1781 {
1782         Key *kp;
1783         int i;
1784
1785         /* Check for mapped keys out of X11 function keys. */
1786         for (i = 0; i < LEN(mappedkeys); i++) {
1787                 if (mappedkeys[i] == k)
1788                         break;
1789         }
1790         if (i == LEN(mappedkeys)) {
1791                 if ((k & 0xFFFF) < 0xFD00)
1792                         return NULL;
1793         }
1794
1795         for (kp = key; kp < key + LEN(key); kp++) {
1796                 if (kp->k != k)
1797                         continue;
1798
1799                 if (!match(kp->mask, state))
1800                         continue;
1801
1802                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1803                         continue;
1804                 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1805                         continue;
1806
1807                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1808                         continue;
1809
1810                 return kp->s;
1811         }
1812
1813         return NULL;
1814 }
1815
1816 void
1817 kpress(XEvent *ev)
1818 {
1819         XKeyEvent *e = &ev->xkey;
1820         KeySym ksym;
1821         char buf[64], *customkey;
1822         int len;
1823         Rune c;
1824         Status status;
1825         Shortcut *bp;
1826
1827         if (IS_SET(MODE_KBDLOCK))
1828                 return;
1829
1830         if (xw.ime.xic)
1831                 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1832         else
1833                 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1834         /* 1. shortcuts */
1835         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1836                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1837                         bp->func(&(bp->arg));
1838                         return;
1839                 }
1840         }
1841
1842         /* 2. custom keys from config.h */
1843         if ((customkey = kmap(ksym, e->state))) {
1844                 ttywrite(customkey, strlen(customkey), 1);
1845                 return;
1846         }
1847
1848         /* 3. composed string from input method */
1849         if (len == 0)
1850                 return;
1851         if (len == 1 && e->state & Mod1Mask) {
1852                 if (IS_SET(MODE_8BIT)) {
1853                         if (*buf < 0177) {
1854                                 c = *buf | 0x80;
1855                                 len = utf8encode(c, buf);
1856                         }
1857                 } else {
1858                         buf[1] = buf[0];
1859                         buf[0] = '\033';
1860                         len = 2;
1861                 }
1862         }
1863         ttywrite(buf, len, 1);
1864 }
1865
1866 void
1867 cmessage(XEvent *e)
1868 {
1869         /*
1870          * See xembed specs
1871          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1872          */
1873         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1874                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1875                         win.mode |= MODE_FOCUSED;
1876                         xseturgency(0);
1877                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1878                         win.mode &= ~MODE_FOCUSED;
1879                 }
1880         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1881                 ttyhangup();
1882                 exit(0);
1883         }
1884 }
1885
1886 void
1887 resize(XEvent *e)
1888 {
1889         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1890                 return;
1891
1892         cresize(e->xconfigure.width, e->xconfigure.height);
1893 }
1894
1895 void
1896 run(void)
1897 {
1898         XEvent ev;
1899         int w = win.w, h = win.h;
1900         fd_set rfd;
1901         int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1902         struct timespec seltv, *tv, now, lastblink, trigger;
1903         double timeout;
1904
1905         /* Waiting for window mapping */
1906         do {
1907                 XNextEvent(xw.dpy, &ev);
1908                 /*
1909                  * This XFilterEvent call is required because of XOpenIM. It
1910                  * does filter out the key event and some client message for
1911                  * the input method too.
1912                  */
1913                 if (XFilterEvent(&ev, None))
1914                         continue;
1915                 if (ev.type == ConfigureNotify) {
1916                         w = ev.xconfigure.width;
1917                         h = ev.xconfigure.height;
1918                 }
1919         } while (ev.type != MapNotify);
1920
1921         ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1922         cresize(w, h);
1923
1924         for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1925                 FD_ZERO(&rfd);
1926                 FD_SET(ttyfd, &rfd);
1927                 FD_SET(xfd, &rfd);
1928
1929                 if (XPending(xw.dpy))
1930                         timeout = 0;  /* existing events might not set xfd */
1931
1932                 seltv.tv_sec = timeout / 1E3;
1933                 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1934                 tv = timeout >= 0 ? &seltv : NULL;
1935
1936                 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1937                         if (errno == EINTR)
1938                                 continue;
1939                         die("select failed: %s\n", strerror(errno));
1940                 }
1941                 clock_gettime(CLOCK_MONOTONIC, &now);
1942
1943                 if (FD_ISSET(ttyfd, &rfd))
1944                         ttyread();
1945
1946                 xev = 0;
1947                 while (XPending(xw.dpy)) {
1948                         xev = 1;
1949                         XNextEvent(xw.dpy, &ev);
1950                         if (XFilterEvent(&ev, None))
1951                                 continue;
1952                         if (handler[ev.type])
1953                                 (handler[ev.type])(&ev);
1954                 }
1955
1956                 /*
1957                  * To reduce flicker and tearing, when new content or event
1958                  * triggers drawing, we first wait a bit to ensure we got
1959                  * everything, and if nothing new arrives - we draw.
1960                  * We start with trying to wait minlatency ms. If more content
1961                  * arrives sooner, we retry with shorter and shorter periods,
1962                  * and eventually draw even without idle after maxlatency ms.
1963                  * Typically this results in low latency while interacting,
1964                  * maximum latency intervals during `cat huge.txt`, and perfect
1965                  * sync with periodic updates from animations/key-repeats/etc.
1966                  */
1967                 if (FD_ISSET(ttyfd, &rfd) || xev) {
1968                         if (!drawing) {
1969                                 trigger = now;
1970                                 drawing = 1;
1971                         }
1972                         timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1973                                   / maxlatency * minlatency;
1974                         if (timeout > 0)
1975                                 continue;  /* we have time, try to find idle */
1976                 }
1977
1978                 /* idle detected or maxlatency exhausted -> draw */
1979                 timeout = -1;
1980                 if (blinktimeout && tattrset(ATTR_BLINK)) {
1981                         timeout = blinktimeout - TIMEDIFF(now, lastblink);
1982                         if (timeout <= 0) {
1983                                 if (-timeout > blinktimeout) /* start visible */
1984                                         win.mode |= MODE_BLINK;
1985                                 win.mode ^= MODE_BLINK;
1986                                 tsetdirtattr(ATTR_BLINK);
1987                                 lastblink = now;
1988                                 timeout = blinktimeout;
1989                         }
1990                 }
1991
1992                 draw();
1993                 XFlush(xw.dpy);
1994                 drawing = 0;
1995         }
1996 }
1997
1998 void
1999 usage(void)
2000 {
2001         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2002             " [-n name] [-o file]\n"
2003             "          [-T title] [-t title] [-w windowid]"
2004             " [[-e] command [args ...]]\n"
2005             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
2006             " [-n name] [-o file]\n"
2007             "          [-T title] [-t title] [-w windowid] -l line"
2008             " [stty_args ...]\n", argv0, argv0);
2009 }
2010
2011 int
2012 main(int argc, char *argv[])
2013 {
2014         xw.l = xw.t = 0;
2015         xw.isfixed = False;
2016         xsetcursor(cursorshape);
2017
2018         ARGBEGIN {
2019         case 'a':
2020                 allowaltscreen = 0;
2021                 break;
2022         case 'c':
2023                 opt_class = EARGF(usage());
2024                 break;
2025         case 'e':
2026                 if (argc > 0)
2027                         --argc, ++argv;
2028                 goto run;
2029         case 'f':
2030                 opt_font = EARGF(usage());
2031                 break;
2032         case 'g':
2033                 xw.gm = XParseGeometry(EARGF(usage()),
2034                                 &xw.l, &xw.t, &cols, &rows);
2035                 break;
2036         case 'i':
2037                 xw.isfixed = 1;
2038                 break;
2039         case 'o':
2040                 opt_io = EARGF(usage());
2041                 break;
2042         case 'l':
2043                 opt_line = EARGF(usage());
2044                 break;
2045         case 'n':
2046                 opt_name = EARGF(usage());
2047                 break;
2048         case 't':
2049         case 'T':
2050                 opt_title = EARGF(usage());
2051                 break;
2052         case 'w':
2053                 opt_embed = EARGF(usage());
2054                 break;
2055         case 'v':
2056                 die("%s " VERSION "\n", argv0);
2057                 break;
2058         default:
2059                 usage();
2060         } ARGEND;
2061
2062 run:
2063         if (argc > 0) /* eat all remaining arguments */
2064                 opt_cmd = argv;
2065
2066         if (!opt_title)
2067                 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2068
2069         setlocale(LC_CTYPE, "");
2070         XSetLocaleModifiers("");
2071         cols = MAX(cols, 1);
2072         rows = MAX(rows, 1);
2073         tnew(cols, rows);
2074         xinit(cols, rows);
2075         xsetenv();
2076         selinit();
2077         run();
2078
2079         return 0;
2080 }