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