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