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