]> git.armaanb.net Git - st.git/blob - x.c
Move terminal-related selection logic into st.c
[st.git] / x.c
1 /* See LICENSE for license details. */
2 #include <errno.h>
3 #include <locale.h>
4 #include <signal.h>
5 #include <stdint.h>
6 #include <sys/select.h>
7 #include <time.h>
8 #include <unistd.h>
9 #include <libgen.h>
10 #include <X11/Xatom.h>
11 #include <X11/Xlib.h>
12 #include <X11/Xutil.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
17
18 static char *argv0;
19 #include "arg.h"
20 #include "st.h"
21 #include "win.h"
22
23 /* types used in config.h */
24 typedef struct {
25         uint mod;
26         KeySym keysym;
27         void (*func)(const Arg *);
28         const Arg arg;
29 } Shortcut;
30
31 typedef struct {
32         uint b;
33         uint mask;
34         char *s;
35 } MouseShortcut;
36
37 typedef struct {
38         KeySym k;
39         uint mask;
40         char *s;
41         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
42         signed char appkey;    /* application keypad */
43         signed char appcursor; /* application cursor */
44         signed char crlf;      /* crlf mode          */
45 } Key;
46
47 /* X modifiers */
48 #define XK_ANY_MOD    UINT_MAX
49 #define XK_NO_MOD     0
50 #define XK_SWITCH_MOD (1<<13)
51
52 /* function definitions used in config.h */
53 static void clipcopy(const Arg *);
54 static void clippaste(const Arg *);
55 static void selpaste(const Arg *);
56 static void zoom(const Arg *);
57 static void zoomabs(const Arg *);
58 static void zoomreset(const Arg *);
59
60 /* config.h for applying patches and the configuration. */
61 #include "config.h"
62
63 /* XEMBED messages */
64 #define XEMBED_FOCUS_IN  4
65 #define XEMBED_FOCUS_OUT 5
66
67 /* macros */
68 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
69 #define TRUEGREEN(x)            (((x) & 0xff00))
70 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
71
72 typedef XftDraw *Draw;
73 typedef XftColor Color;
74 typedef XftGlyphFontSpec GlyphFontSpec;
75
76 /* Purely graphic info */
77 typedef struct {
78         Display *dpy;
79         Colormap cmap;
80         Window win;
81         Drawable buf;
82         GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
83         Atom xembed, wmdeletewin, netwmname, netwmpid;
84         XIM xim;
85         XIC xic;
86         Draw draw;
87         Visual *vis;
88         XSetWindowAttributes attrs;
89         int scr;
90         int isfixed; /* is fixed geometry? */
91         int l, t; /* left and top offset */
92         int gm; /* geometry mask */
93 } XWindow;
94
95 typedef struct {
96         Atom xtarget;
97         char *primary, *clipboard;
98         struct timespec tclick1;
99         struct timespec tclick2;
100 } XSelection;
101
102 /* Font structure */
103 #define Font Font_
104 typedef struct {
105         int height;
106         int width;
107         int ascent;
108         int descent;
109         int badslant;
110         int badweight;
111         short lbearing;
112         short rbearing;
113         XftFont *match;
114         FcFontSet *set;
115         FcPattern *pattern;
116 } Font;
117
118 /* Drawing Context */
119 typedef struct {
120         Color *col;
121         size_t collen;
122         Font font, bfont, ifont, ibfont;
123         GC gc;
124 } DC;
125
126 static inline ushort sixd_to_16bit(int);
127 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
128 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
129 static void xdrawglyph(Glyph, int, int);
130 static void xclear(int, int, int, int);
131 static void xdrawcursor(void);
132 static int xgeommasktogravity(int);
133 static void xinit(void);
134 static void cresize(int, int);
135 static void xresize(int, int);
136 static int xloadfont(Font *, FcPattern *);
137 static void xloadfonts(char *, double);
138 static void xunloadfont(Font *);
139 static void xunloadfonts(void);
140 static void xsetenv(void);
141 static void xseturgency(int);
142 static int x2col(int);
143 static int y2row(int);
144
145 static void expose(XEvent *);
146 static void visibility(XEvent *);
147 static void unmap(XEvent *);
148 static void kpress(XEvent *);
149 static void cmessage(XEvent *);
150 static void resize(XEvent *);
151 static void focus(XEvent *);
152 static void brelease(XEvent *);
153 static void bpress(XEvent *);
154 static void bmotion(XEvent *);
155 static void propnotify(XEvent *);
156 static void selnotify(XEvent *);
157 static void selclear_(XEvent *);
158 static void selrequest(XEvent *);
159 static void setsel(char *, Time);
160 static void mousesel(XEvent *);
161 static void mousereport(XEvent *);
162 static char *kmap(KeySym, uint);
163 static int match(uint, uint);
164
165 static void run(void);
166 static void usage(void);
167
168 static void (*handler[LASTEvent])(XEvent *) = {
169         [KeyPress] = kpress,
170         [ClientMessage] = cmessage,
171         [ConfigureNotify] = resize,
172         [VisibilityNotify] = visibility,
173         [UnmapNotify] = unmap,
174         [Expose] = expose,
175         [FocusIn] = focus,
176         [FocusOut] = focus,
177         [MotionNotify] = bmotion,
178         [ButtonPress] = bpress,
179         [ButtonRelease] = brelease,
180 /*
181  * Uncomment if you want the selection to disappear when you select something
182  * different in another window.
183  */
184 /*      [SelectionClear] = selclear_, */
185         [SelectionNotify] = selnotify,
186 /*
187  * PropertyNotify is only turned on when there is some INCR transfer happening
188  * for the selection retrieval.
189  */
190         [PropertyNotify] = propnotify,
191         [SelectionRequest] = selrequest,
192 };
193
194 /* Globals */
195 static DC dc;
196 static XWindow xw;
197 static XSelection xsel;
198 static TermWindow win;
199
200 enum window_state {
201         WIN_VISIBLE = 1,
202         WIN_FOCUSED = 2
203 };
204
205 /* Font Ring Cache */
206 enum {
207         FRC_NORMAL,
208         FRC_ITALIC,
209         FRC_BOLD,
210         FRC_ITALICBOLD
211 };
212
213 typedef struct {
214         XftFont *font;
215         int flags;
216         Rune unicodep;
217 } Fontcache;
218
219 /* Fontcache is an array now. A new font will be appended to the array. */
220 static Fontcache frc[16];
221 static int frclen = 0;
222 static char *usedfont = NULL;
223 static double usedfontsize = 0;
224 static double defaultfontsize = 0;
225
226 static char *opt_class = NULL;
227 static char **opt_cmd  = NULL;
228 static char *opt_embed = NULL;
229 static char *opt_font  = NULL;
230 static char *opt_io    = NULL;
231 static char *opt_line  = NULL;
232 static char *opt_name  = NULL;
233 static char *opt_title = NULL;
234
235 void
236 clipcopy(const Arg *dummy)
237 {
238         Atom clipboard;
239
240         if (xsel.clipboard != NULL)
241                 free(xsel.clipboard);
242
243         if (xsel.primary != NULL) {
244                 xsel.clipboard = xstrdup(xsel.primary);
245                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
246                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
247         }
248 }
249
250 void
251 clippaste(const Arg *dummy)
252 {
253         Atom clipboard;
254
255         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
256         XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
257                         xw.win, CurrentTime);
258 }
259
260 void
261 selpaste(const Arg *dummy)
262 {
263         XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
264                         xw.win, CurrentTime);
265 }
266
267 void
268 zoom(const Arg *arg)
269 {
270         Arg larg;
271
272         larg.f = usedfontsize + arg->f;
273         zoomabs(&larg);
274 }
275
276 void
277 zoomabs(const Arg *arg)
278 {
279         xunloadfonts();
280         xloadfonts(usedfont, arg->f);
281         cresize(0, 0);
282         redraw();
283         xhints();
284 }
285
286 void
287 zoomreset(const Arg *arg)
288 {
289         Arg larg;
290
291         if (defaultfontsize > 0) {
292                 larg.f = defaultfontsize;
293                 zoomabs(&larg);
294         }
295 }
296
297 int
298 x2col(int x)
299 {
300         x -= borderpx;
301         x /= win.cw;
302
303         return LIMIT(x, 0, term.col-1);
304 }
305
306 int
307 y2row(int y)
308 {
309         y -= borderpx;
310         y /= win.ch;
311
312         return LIMIT(y, 0, term.row-1);
313 }
314
315 void
316 mousesel(XEvent *e)
317 {
318         int type, seltype = SEL_REGULAR;
319         uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
320
321         for (type = 1; type < LEN(selmasks); ++type) {
322                 if (match(selmasks[type], state)) {
323                         seltype = type;
324                         break;
325                 }
326         }
327
328         selextend(x2col(e->xbutton.x), y2row(e->xbutton.y), seltype);
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);
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                         ttysend(ms->s, strlen(ms->s));
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);
523                 ttysend((char *)data, nitems * format / 8);
524                 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
525                         ttywrite("\033[201~", 6);
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                 if (sel.mode == SEL_READY) {
637                         mousesel(e);
638                         setsel(getsel(), e->xbutton.time);
639                 } else
640                         selclear_(NULL);
641                 sel.mode = SEL_IDLE;
642         }
643 }
644
645 void
646 bmotion(XEvent *e)
647 {
648         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
649                 mousereport(e);
650                 return;
651         }
652
653         if (!sel.mode)
654                 return;
655
656         sel.mode = SEL_READY;
657         mousesel(e);
658 }
659
660 void
661 cresize(int width, int height)
662 {
663         int col, row;
664
665         if (width != 0)
666                 win.w = width;
667         if (height != 0)
668                 win.h = height;
669
670         col = (win.w - 2 * borderpx) / win.cw;
671         row = (win.h - 2 * borderpx) / win.ch;
672
673         tresize(col, row);
674         xresize(col, row);
675         ttyresize(win.tw, win.th);
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(LEN(colorname), 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         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1109         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1110         xsel.primary = NULL;
1111         xsel.clipboard = NULL;
1112         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1113         if (xsel.xtarget == None)
1114                 xsel.xtarget = XA_STRING;
1115 }
1116
1117 int
1118 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1119 {
1120         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1121         ushort mode, prevmode = USHRT_MAX;
1122         Font *font = &dc.font;
1123         int frcflags = FRC_NORMAL;
1124         float runewidth = win.cw;
1125         Rune rune;
1126         FT_UInt glyphidx;
1127         FcResult fcres;
1128         FcPattern *fcpattern, *fontpattern;
1129         FcFontSet *fcsets[] = { NULL };
1130         FcCharSet *fccharset;
1131         int i, f, numspecs = 0;
1132
1133         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1134                 /* Fetch rune and mode for current glyph. */
1135                 rune = glyphs[i].u;
1136                 mode = glyphs[i].mode;
1137
1138                 /* Skip dummy wide-character spacing. */
1139                 if (mode == ATTR_WDUMMY)
1140                         continue;
1141
1142                 /* Determine font for glyph if different from previous glyph. */
1143                 if (prevmode != mode) {
1144                         prevmode = mode;
1145                         font = &dc.font;
1146                         frcflags = FRC_NORMAL;
1147                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1148                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1149                                 font = &dc.ibfont;
1150                                 frcflags = FRC_ITALICBOLD;
1151                         } else if (mode & ATTR_ITALIC) {
1152                                 font = &dc.ifont;
1153                                 frcflags = FRC_ITALIC;
1154                         } else if (mode & ATTR_BOLD) {
1155                                 font = &dc.bfont;
1156                                 frcflags = FRC_BOLD;
1157                         }
1158                         yp = winy + font->ascent;
1159                 }
1160
1161                 /* Lookup character index with default font. */
1162                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1163                 if (glyphidx) {
1164                         specs[numspecs].font = font->match;
1165                         specs[numspecs].glyph = glyphidx;
1166                         specs[numspecs].x = (short)xp;
1167                         specs[numspecs].y = (short)yp;
1168                         xp += runewidth;
1169                         numspecs++;
1170                         continue;
1171                 }
1172
1173                 /* Fallback on font cache, search the font cache for match. */
1174                 for (f = 0; f < frclen; f++) {
1175                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1176                         /* Everything correct. */
1177                         if (glyphidx && frc[f].flags == frcflags)
1178                                 break;
1179                         /* We got a default font for a not found glyph. */
1180                         if (!glyphidx && frc[f].flags == frcflags
1181                                         && frc[f].unicodep == rune) {
1182                                 break;
1183                         }
1184                 }
1185
1186                 /* Nothing was found. Use fontconfig to find matching font. */
1187                 if (f >= frclen) {
1188                         if (!font->set)
1189                                 font->set = FcFontSort(0, font->pattern,
1190                                                        1, 0, &fcres);
1191                         fcsets[0] = font->set;
1192
1193                         /*
1194                          * Nothing was found in the cache. Now use
1195                          * some dozen of Fontconfig calls to get the
1196                          * font for one single character.
1197                          *
1198                          * Xft and fontconfig are design failures.
1199                          */
1200                         fcpattern = FcPatternDuplicate(font->pattern);
1201                         fccharset = FcCharSetCreate();
1202
1203                         FcCharSetAddChar(fccharset, rune);
1204                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1205                                         fccharset);
1206                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1207
1208                         FcConfigSubstitute(0, fcpattern,
1209                                         FcMatchPattern);
1210                         FcDefaultSubstitute(fcpattern);
1211
1212                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1213                                         fcpattern, &fcres);
1214
1215                         /*
1216                          * Overwrite or create the new cache entry.
1217                          */
1218                         if (frclen >= LEN(frc)) {
1219                                 frclen = LEN(frc) - 1;
1220                                 XftFontClose(xw.dpy, frc[frclen].font);
1221                                 frc[frclen].unicodep = 0;
1222                         }
1223
1224                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1225                                         fontpattern);
1226                         if (!frc[frclen].font)
1227                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1228                                         strerror(errno));
1229                         frc[frclen].flags = frcflags;
1230                         frc[frclen].unicodep = rune;
1231
1232                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1233
1234                         f = frclen;
1235                         frclen++;
1236
1237                         FcPatternDestroy(fcpattern);
1238                         FcCharSetDestroy(fccharset);
1239                 }
1240
1241                 specs[numspecs].font = frc[f].font;
1242                 specs[numspecs].glyph = glyphidx;
1243                 specs[numspecs].x = (short)xp;
1244                 specs[numspecs].y = (short)yp;
1245                 xp += runewidth;
1246                 numspecs++;
1247         }
1248
1249         return numspecs;
1250 }
1251
1252 void
1253 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1254 {
1255         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1256         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1257             width = charlen * win.cw;
1258         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1259         XRenderColor colfg, colbg;
1260         XRectangle r;
1261
1262         /* Fallback on color display for attributes not supported by the font */
1263         if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1264                 if (dc.ibfont.badslant || dc.ibfont.badweight)
1265                         base.fg = defaultattr;
1266         } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1267             (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1268                 base.fg = defaultattr;
1269         }
1270
1271         if (IS_TRUECOL(base.fg)) {
1272                 colfg.alpha = 0xffff;
1273                 colfg.red = TRUERED(base.fg);
1274                 colfg.green = TRUEGREEN(base.fg);
1275                 colfg.blue = TRUEBLUE(base.fg);
1276                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1277                 fg = &truefg;
1278         } else {
1279                 fg = &dc.col[base.fg];
1280         }
1281
1282         if (IS_TRUECOL(base.bg)) {
1283                 colbg.alpha = 0xffff;
1284                 colbg.green = TRUEGREEN(base.bg);
1285                 colbg.red = TRUERED(base.bg);
1286                 colbg.blue = TRUEBLUE(base.bg);
1287                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1288                 bg = &truebg;
1289         } else {
1290                 bg = &dc.col[base.bg];
1291         }
1292
1293         /* Change basic system colors [0-7] to bright system colors [8-15] */
1294         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1295                 fg = &dc.col[base.fg + 8];
1296
1297         if (IS_SET(MODE_REVERSE)) {
1298                 if (fg == &dc.col[defaultfg]) {
1299                         fg = &dc.col[defaultbg];
1300                 } else {
1301                         colfg.red = ~fg->color.red;
1302                         colfg.green = ~fg->color.green;
1303                         colfg.blue = ~fg->color.blue;
1304                         colfg.alpha = fg->color.alpha;
1305                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1306                                         &revfg);
1307                         fg = &revfg;
1308                 }
1309
1310                 if (bg == &dc.col[defaultbg]) {
1311                         bg = &dc.col[defaultfg];
1312                 } else {
1313                         colbg.red = ~bg->color.red;
1314                         colbg.green = ~bg->color.green;
1315                         colbg.blue = ~bg->color.blue;
1316                         colbg.alpha = bg->color.alpha;
1317                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1318                                         &revbg);
1319                         bg = &revbg;
1320                 }
1321         }
1322
1323         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1324                 colfg.red = fg->color.red / 2;
1325                 colfg.green = fg->color.green / 2;
1326                 colfg.blue = fg->color.blue / 2;
1327                 colfg.alpha = fg->color.alpha;
1328                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1329                 fg = &revfg;
1330         }
1331
1332
1333         if (base.mode & ATTR_REVERSE) {
1334                 temp = fg;
1335                 fg = bg;
1336                 bg = temp;
1337         }
1338
1339         if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1340                 fg = bg;
1341
1342         if (base.mode & ATTR_INVISIBLE)
1343                 fg = bg;
1344
1345         /* Intelligent cleaning up of the borders. */
1346         if (x == 0) {
1347                 xclear(0, (y == 0)? 0 : winy, borderpx,
1348                         winy + win.ch + ((y >= term.row-1)? win.h : 0));
1349         }
1350         if (x + charlen >= term.col) {
1351                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1352                         ((y >= term.row-1)? win.h : (winy + win.ch)));
1353         }
1354         if (y == 0)
1355                 xclear(winx, 0, winx + width, borderpx);
1356         if (y == term.row-1)
1357                 xclear(winx, winy + win.ch, winx + width, win.h);
1358
1359         /* Clean up the region we want to draw to. */
1360         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1361
1362         /* Set the clip region because Xft is sometimes dirty. */
1363         r.x = 0;
1364         r.y = 0;
1365         r.height = win.ch;
1366         r.width = width;
1367         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1368
1369         /* Render the glyphs. */
1370         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1371
1372         /* Render underline and strikethrough. */
1373         if (base.mode & ATTR_UNDERLINE) {
1374                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1375                                 width, 1);
1376         }
1377
1378         if (base.mode & ATTR_STRUCK) {
1379                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1380                                 width, 1);
1381         }
1382
1383         /* Reset clip to none. */
1384         XftDrawSetClip(xw.draw, 0);
1385 }
1386
1387 void
1388 xdrawglyph(Glyph g, int x, int y)
1389 {
1390         int numspecs;
1391         XftGlyphFontSpec spec;
1392
1393         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1394         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1395 }
1396
1397 void
1398 xdrawcursor(void)
1399 {
1400         static int oldx = 0, oldy = 0;
1401         int curx;
1402         Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1403         Color drawcol;
1404
1405         LIMIT(oldx, 0, term.col-1);
1406         LIMIT(oldy, 0, term.row-1);
1407
1408         curx = term.c.x;
1409
1410         /* adjust position if in dummy */
1411         if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1412                 oldx--;
1413         if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1414                 curx--;
1415
1416         /* remove the old cursor */
1417         og = term.line[oldy][oldx];
1418         if (selected(oldx, oldy))
1419                 og.mode ^= ATTR_REVERSE;
1420         xdrawglyph(og, oldx, oldy);
1421
1422         g.u = term.line[term.c.y][term.c.x].u;
1423         g.mode |= term.line[term.c.y][term.c.x].mode &
1424                   (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1425
1426         /*
1427          * Select the right color for the right mode.
1428          */
1429         if (IS_SET(MODE_REVERSE)) {
1430                 g.mode |= ATTR_REVERSE;
1431                 g.bg = defaultfg;
1432                 if (selected(term.c.x, term.c.y)) {
1433                         drawcol = dc.col[defaultcs];
1434                         g.fg = defaultrcs;
1435                 } else {
1436                         drawcol = dc.col[defaultrcs];
1437                         g.fg = defaultcs;
1438                 }
1439         } else {
1440                 if (selected(term.c.x, term.c.y)) {
1441                         drawcol = dc.col[defaultrcs];
1442                         g.fg = defaultfg;
1443                         g.bg = defaultrcs;
1444                 } else {
1445                         drawcol = dc.col[defaultcs];
1446                 }
1447         }
1448
1449         if (IS_SET(MODE_HIDE))
1450                 return;
1451
1452         /* draw the new one */
1453         if (win.state & WIN_FOCUSED) {
1454                 switch (win.cursor) {
1455                 case 7: /* st extension: snowman */
1456                         utf8decode("☃", &g.u, UTF_SIZ);
1457                 case 0: /* Blinking Block */
1458                 case 1: /* Blinking Block (Default) */
1459                 case 2: /* Steady Block */
1460                         g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1461                         xdrawglyph(g, term.c.x, term.c.y);
1462                         break;
1463                 case 3: /* Blinking Underline */
1464                 case 4: /* Steady Underline */
1465                         XftDrawRect(xw.draw, &drawcol,
1466                                         borderpx + curx * win.cw,
1467                                         borderpx + (term.c.y + 1) * win.ch - \
1468                                                 cursorthickness,
1469                                         win.cw, cursorthickness);
1470                         break;
1471                 case 5: /* Blinking bar */
1472                 case 6: /* Steady bar */
1473                         XftDrawRect(xw.draw, &drawcol,
1474                                         borderpx + curx * win.cw,
1475                                         borderpx + term.c.y * win.ch,
1476                                         cursorthickness, win.ch);
1477                         break;
1478                 }
1479         } else {
1480                 XftDrawRect(xw.draw, &drawcol,
1481                                 borderpx + curx * win.cw,
1482                                 borderpx + term.c.y * win.ch,
1483                                 win.cw - 1, 1);
1484                 XftDrawRect(xw.draw, &drawcol,
1485                                 borderpx + curx * win.cw,
1486                                 borderpx + term.c.y * win.ch,
1487                                 1, win.ch - 1);
1488                 XftDrawRect(xw.draw, &drawcol,
1489                                 borderpx + (curx + 1) * win.cw - 1,
1490                                 borderpx + term.c.y * win.ch,
1491                                 1, win.ch - 1);
1492                 XftDrawRect(xw.draw, &drawcol,
1493                                 borderpx + curx * win.cw,
1494                                 borderpx + (term.c.y + 1) * win.ch - 1,
1495                                 win.cw, 1);
1496         }
1497         oldx = curx, oldy = term.c.y;
1498 }
1499
1500 void
1501 xsetenv(void)
1502 {
1503         char buf[sizeof(long) * 8 + 1];
1504
1505         snprintf(buf, sizeof(buf), "%lu", xw.win);
1506         setenv("WINDOWID", buf, 1);
1507 }
1508
1509 void
1510 xsettitle(char *p)
1511 {
1512         XTextProperty prop;
1513         DEFAULT(p, "st");
1514
1515         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1516                         &prop);
1517         XSetWMName(xw.dpy, xw.win, &prop);
1518         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1519         XFree(prop.value);
1520 }
1521
1522 void
1523 draw(void)
1524 {
1525         drawregion(0, 0, term.col, term.row);
1526         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1527                         win.h, 0, 0);
1528         XSetForeground(xw.dpy, dc.gc,
1529                         dc.col[IS_SET(MODE_REVERSE)?
1530                                 defaultfg : defaultbg].pixel);
1531 }
1532
1533 void
1534 drawregion(int x1, int y1, int x2, int y2)
1535 {
1536         int i, x, y, ox, numspecs;
1537         Glyph base, new;
1538         XftGlyphFontSpec *specs;
1539
1540         if (!(win.state & WIN_VISIBLE))
1541                 return;
1542
1543         for (y = y1; y < y2; y++) {
1544                 if (!term.dirty[y])
1545                         continue;
1546
1547                 term.dirty[y] = 0;
1548
1549                 specs = xw.specbuf;
1550                 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1551
1552                 i = ox = 0;
1553                 for (x = x1; x < x2 && i < numspecs; x++) {
1554                         new = term.line[y][x];
1555                         if (new.mode == ATTR_WDUMMY)
1556                                 continue;
1557                         if (selected(x, y))
1558                                 new.mode ^= ATTR_REVERSE;
1559                         if (i > 0 && ATTRCMP(base, new)) {
1560                                 xdrawglyphfontspecs(specs, base, i, ox, y);
1561                                 specs += i;
1562                                 numspecs -= i;
1563                                 i = 0;
1564                         }
1565                         if (i == 0) {
1566                                 ox = x;
1567                                 base = new;
1568                         }
1569                         i++;
1570                 }
1571                 if (i > 0)
1572                         xdrawglyphfontspecs(specs, base, i, ox, y);
1573         }
1574         xdrawcursor();
1575 }
1576
1577 void
1578 expose(XEvent *ev)
1579 {
1580         redraw();
1581 }
1582
1583 void
1584 visibility(XEvent *ev)
1585 {
1586         XVisibilityEvent *e = &ev->xvisibility;
1587
1588         MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1589 }
1590
1591 void
1592 unmap(XEvent *ev)
1593 {
1594         win.state &= ~WIN_VISIBLE;
1595 }
1596
1597 void
1598 xsetpointermotion(int set)
1599 {
1600         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1601         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1602 }
1603
1604 int
1605 xsetcursor(int cursor)
1606 {
1607         DEFAULT(cursor, 1);
1608         if (!BETWEEN(cursor, 0, 6))
1609                 return 1;
1610         win.cursor = cursor;
1611         return 0;
1612 }
1613
1614 void
1615 xseturgency(int add)
1616 {
1617         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1618
1619         MODBIT(h->flags, add, XUrgencyHint);
1620         XSetWMHints(xw.dpy, xw.win, h);
1621         XFree(h);
1622 }
1623
1624 void
1625 xbell(void)
1626 {
1627         if (!(win.state & WIN_FOCUSED))
1628                 xseturgency(1);
1629         if (bellvolume)
1630                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1631 }
1632
1633 void
1634 focus(XEvent *ev)
1635 {
1636         XFocusChangeEvent *e = &ev->xfocus;
1637
1638         if (e->mode == NotifyGrab)
1639                 return;
1640
1641         if (ev->type == FocusIn) {
1642                 XSetICFocus(xw.xic);
1643                 win.state |= WIN_FOCUSED;
1644                 xseturgency(0);
1645                 if (IS_SET(MODE_FOCUS))
1646                         ttywrite("\033[I", 3);
1647         } else {
1648                 XUnsetICFocus(xw.xic);
1649                 win.state &= ~WIN_FOCUSED;
1650                 if (IS_SET(MODE_FOCUS))
1651                         ttywrite("\033[O", 3);
1652         }
1653 }
1654
1655 int
1656 match(uint mask, uint state)
1657 {
1658         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1659 }
1660
1661 char*
1662 kmap(KeySym k, uint state)
1663 {
1664         Key *kp;
1665         int i;
1666
1667         /* Check for mapped keys out of X11 function keys. */
1668         for (i = 0; i < LEN(mappedkeys); i++) {
1669                 if (mappedkeys[i] == k)
1670                         break;
1671         }
1672         if (i == LEN(mappedkeys)) {
1673                 if ((k & 0xFFFF) < 0xFD00)
1674                         return NULL;
1675         }
1676
1677         for (kp = key; kp < key + LEN(key); kp++) {
1678                 if (kp->k != k)
1679                         continue;
1680
1681                 if (!match(kp->mask, state))
1682                         continue;
1683
1684                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1685                         continue;
1686                 if (term.numlock && kp->appkey == 2)
1687                         continue;
1688
1689                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1690                         continue;
1691
1692                 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
1693                         continue;
1694
1695                 return kp->s;
1696         }
1697
1698         return NULL;
1699 }
1700
1701 void
1702 kpress(XEvent *ev)
1703 {
1704         XKeyEvent *e = &ev->xkey;
1705         KeySym ksym;
1706         char buf[32], *customkey;
1707         int len;
1708         Rune c;
1709         Status status;
1710         Shortcut *bp;
1711
1712         if (IS_SET(MODE_KBDLOCK))
1713                 return;
1714
1715         len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1716         /* 1. shortcuts */
1717         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1718                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1719                         bp->func(&(bp->arg));
1720                         return;
1721                 }
1722         }
1723
1724         /* 2. custom keys from config.h */
1725         if ((customkey = kmap(ksym, e->state))) {
1726                 ttysend(customkey, strlen(customkey));
1727                 return;
1728         }
1729
1730         /* 3. composed string from input method */
1731         if (len == 0)
1732                 return;
1733         if (len == 1 && e->state & Mod1Mask) {
1734                 if (IS_SET(MODE_8BIT)) {
1735                         if (*buf < 0177) {
1736                                 c = *buf | 0x80;
1737                                 len = utf8encode(c, buf);
1738                         }
1739                 } else {
1740                         buf[1] = buf[0];
1741                         buf[0] = '\033';
1742                         len = 2;
1743                 }
1744         }
1745         ttysend(buf, len);
1746 }
1747
1748
1749 void
1750 cmessage(XEvent *e)
1751 {
1752         /*
1753          * See xembed specs
1754          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1755          */
1756         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1757                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1758                         win.state |= WIN_FOCUSED;
1759                         xseturgency(0);
1760                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1761                         win.state &= ~WIN_FOCUSED;
1762                 }
1763         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1764                 /* Send SIGHUP to shell */
1765                 kill(pid, SIGHUP);
1766                 exit(0);
1767         }
1768 }
1769
1770 void
1771 resize(XEvent *e)
1772 {
1773         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1774                 return;
1775
1776         cresize(e->xconfigure.width, e->xconfigure.height);
1777 }
1778
1779 void
1780 run(void)
1781 {
1782         XEvent ev;
1783         int w = win.w, h = win.h;
1784         fd_set rfd;
1785         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1786         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1787         long deltatime;
1788
1789         /* Waiting for window mapping */
1790         do {
1791                 XNextEvent(xw.dpy, &ev);
1792                 /*
1793                  * This XFilterEvent call is required because of XOpenIM. It
1794                  * does filter out the key event and some client message for
1795                  * the input method too.
1796                  */
1797                 if (XFilterEvent(&ev, None))
1798                         continue;
1799                 if (ev.type == ConfigureNotify) {
1800                         w = ev.xconfigure.width;
1801                         h = ev.xconfigure.height;
1802                 }
1803         } while (ev.type != MapNotify);
1804
1805         ttynew(opt_line, opt_io, opt_cmd);
1806         cresize(w, h);
1807
1808         clock_gettime(CLOCK_MONOTONIC, &last);
1809         lastblink = last;
1810
1811         for (xev = actionfps;;) {
1812                 FD_ZERO(&rfd);
1813                 FD_SET(cmdfd, &rfd);
1814                 FD_SET(xfd, &rfd);
1815
1816                 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1817                         if (errno == EINTR)
1818                                 continue;
1819                         die("select failed: %s\n", strerror(errno));
1820                 }
1821                 if (FD_ISSET(cmdfd, &rfd)) {
1822                         ttyread();
1823                         if (blinktimeout) {
1824                                 blinkset = tattrset(ATTR_BLINK);
1825                                 if (!blinkset)
1826                                         MODBIT(term.mode, 0, MODE_BLINK);
1827                         }
1828                 }
1829
1830                 if (FD_ISSET(xfd, &rfd))
1831                         xev = actionfps;
1832
1833                 clock_gettime(CLOCK_MONOTONIC, &now);
1834                 drawtimeout.tv_sec = 0;
1835                 drawtimeout.tv_nsec =  (1000 * 1E6)/ xfps;
1836                 tv = &drawtimeout;
1837
1838                 dodraw = 0;
1839                 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1840                         tsetdirtattr(ATTR_BLINK);
1841                         term.mode ^= MODE_BLINK;
1842                         lastblink = now;
1843                         dodraw = 1;
1844                 }
1845                 deltatime = TIMEDIFF(now, last);
1846                 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1847                         dodraw = 1;
1848                         last = now;
1849                 }
1850
1851                 if (dodraw) {
1852                         while (XPending(xw.dpy)) {
1853                                 XNextEvent(xw.dpy, &ev);
1854                                 if (XFilterEvent(&ev, None))
1855                                         continue;
1856                                 if (handler[ev.type])
1857                                         (handler[ev.type])(&ev);
1858                         }
1859
1860                         draw();
1861                         XFlush(xw.dpy);
1862
1863                         if (xev && !FD_ISSET(xfd, &rfd))
1864                                 xev--;
1865                         if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1866                                 if (blinkset) {
1867                                         if (TIMEDIFF(now, lastblink) \
1868                                                         > blinktimeout) {
1869                                                 drawtimeout.tv_nsec = 1000;
1870                                         } else {
1871                                                 drawtimeout.tv_nsec = (1E6 * \
1872                                                         (blinktimeout - \
1873                                                         TIMEDIFF(now,
1874                                                                 lastblink)));
1875                                         }
1876                                         drawtimeout.tv_sec = \
1877                                             drawtimeout.tv_nsec / 1E9;
1878                                         drawtimeout.tv_nsec %= (long)1E9;
1879                                 } else {
1880                                         tv = NULL;
1881                                 }
1882                         }
1883                 }
1884         }
1885 }
1886
1887 void
1888 usage(void)
1889 {
1890         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1891             " [-n name] [-o file]\n"
1892             "          [-T title] [-t title] [-w windowid]"
1893             " [[-e] command [args ...]]\n"
1894             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
1895             " [-n name] [-o file]\n"
1896             "          [-T title] [-t title] [-w windowid] -l line"
1897             " [stty_args ...]\n", argv0, argv0);
1898 }
1899
1900 int
1901 main(int argc, char *argv[])
1902 {
1903         xw.l = xw.t = 0;
1904         xw.isfixed = False;
1905         win.cursor = cursorshape;
1906
1907         ARGBEGIN {
1908         case 'a':
1909                 allowaltscreen = 0;
1910                 break;
1911         case 'c':
1912                 opt_class = EARGF(usage());
1913                 break;
1914         case 'e':
1915                 if (argc > 0)
1916                         --argc, ++argv;
1917                 goto run;
1918         case 'f':
1919                 opt_font = EARGF(usage());
1920                 break;
1921         case 'g':
1922                 xw.gm = XParseGeometry(EARGF(usage()),
1923                                 &xw.l, &xw.t, &cols, &rows);
1924                 break;
1925         case 'i':
1926                 xw.isfixed = 1;
1927                 break;
1928         case 'o':
1929                 opt_io = EARGF(usage());
1930                 break;
1931         case 'l':
1932                 opt_line = EARGF(usage());
1933                 break;
1934         case 'n':
1935                 opt_name = EARGF(usage());
1936                 break;
1937         case 't':
1938         case 'T':
1939                 opt_title = EARGF(usage());
1940                 break;
1941         case 'w':
1942                 opt_embed = EARGF(usage());
1943                 break;
1944         case 'v':
1945                 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1946                 break;
1947         default:
1948                 usage();
1949         } ARGEND;
1950
1951 run:
1952         if (argc > 0) {
1953                 /* eat all remaining arguments */
1954                 opt_cmd = argv;
1955                 if (!opt_title && !opt_line)
1956                         opt_title = basename(xstrdup(argv[0]));
1957         }
1958         setlocale(LC_CTYPE, "");
1959         XSetLocaleModifiers("");
1960         tnew(MAX(cols, 1), MAX(rows, 1));
1961         xinit();
1962         xsetenv();
1963         selinit();
1964         run();
1965
1966         return 0;
1967 }