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