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