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