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