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