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