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