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