]> git.armaanb.net Git - st.git/blob - x.c
x: fix XIM handling
[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                                        XNFocusWindow, xw.win,
1051                                        XNDestroyCallback, &icdestroy,
1052                                        NULL);
1053         }
1054         if (xw.ime.xic == NULL)
1055                 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1056
1057         return 1;
1058 }
1059
1060 void
1061 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1062 {
1063         if (ximopen(dpy))
1064                 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1065                                                  ximinstantiate, NULL);
1066 }
1067
1068 void
1069 ximdestroy(XIM xim, XPointer client, XPointer call)
1070 {
1071         xw.ime.xim = NULL;
1072         XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1073                                        ximinstantiate, NULL);
1074         XFree(xw.ime.spotlist);
1075 }
1076
1077 int
1078 xicdestroy(XIC xim, XPointer client, XPointer call)
1079 {
1080         xw.ime.xic = NULL;
1081         return 1;
1082 }
1083
1084 void
1085 xinit(int cols, int rows)
1086 {
1087         XGCValues gcvalues;
1088         Cursor cursor;
1089         Window parent;
1090         pid_t thispid = getpid();
1091         XColor xmousefg, xmousebg;
1092
1093         if (!(xw.dpy = XOpenDisplay(NULL)))
1094                 die("can't open display\n");
1095         xw.scr = XDefaultScreen(xw.dpy);
1096         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1097
1098         /* font */
1099         if (!FcInit())
1100                 die("could not init fontconfig.\n");
1101
1102         usedfont = (opt_font == NULL)? font : opt_font;
1103         xloadfonts(usedfont, 0);
1104
1105         /* colors */
1106         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1107         xloadcols();
1108
1109         /* adjust fixed window geometry */
1110         win.w = 2 * borderpx + cols * win.cw;
1111         win.h = 2 * borderpx + rows * win.ch;
1112         if (xw.gm & XNegative)
1113                 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1114         if (xw.gm & YNegative)
1115                 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1116
1117         /* Events */
1118         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1119         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1120         xw.attrs.bit_gravity = NorthWestGravity;
1121         xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1122                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1123                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1124         xw.attrs.colormap = xw.cmap;
1125
1126         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1127                 parent = XRootWindow(xw.dpy, xw.scr);
1128         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1129                         win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1130                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1131                         | CWEventMask | CWColormap, &xw.attrs);
1132
1133         memset(&gcvalues, 0, sizeof(gcvalues));
1134         gcvalues.graphics_exposures = False;
1135         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1136                         &gcvalues);
1137         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1138                         DefaultDepth(xw.dpy, xw.scr));
1139         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1140         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1141
1142         /* font spec buffer */
1143         xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1144
1145         /* Xft rendering context */
1146         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1147
1148         /* input methods */
1149         if (!ximopen(xw.dpy)) {
1150                 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1151                                                ximinstantiate, NULL);
1152         }
1153
1154         /* white cursor, black outline */
1155         cursor = XCreateFontCursor(xw.dpy, mouseshape);
1156         XDefineCursor(xw.dpy, xw.win, cursor);
1157
1158         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1159                 xmousefg.red   = 0xffff;
1160                 xmousefg.green = 0xffff;
1161                 xmousefg.blue  = 0xffff;
1162         }
1163
1164         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1165                 xmousebg.red   = 0x0000;
1166                 xmousebg.green = 0x0000;
1167                 xmousebg.blue  = 0x0000;
1168         }
1169
1170         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1171
1172         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1173         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1174         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1175         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1176
1177         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1178         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1179                         PropModeReplace, (uchar *)&thispid, 1);
1180
1181         win.mode = MODE_NUMLOCK;
1182         resettitle();
1183         xhints();
1184         XMapWindow(xw.dpy, xw.win);
1185         XSync(xw.dpy, False);
1186
1187         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1188         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1189         xsel.primary = NULL;
1190         xsel.clipboard = NULL;
1191         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1192         if (xsel.xtarget == None)
1193                 xsel.xtarget = XA_STRING;
1194 }
1195
1196 int
1197 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1198 {
1199         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1200         ushort mode, prevmode = USHRT_MAX;
1201         Font *font = &dc.font;
1202         int frcflags = FRC_NORMAL;
1203         float runewidth = win.cw;
1204         Rune rune;
1205         FT_UInt glyphidx;
1206         FcResult fcres;
1207         FcPattern *fcpattern, *fontpattern;
1208         FcFontSet *fcsets[] = { NULL };
1209         FcCharSet *fccharset;
1210         int i, f, numspecs = 0;
1211
1212         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1213                 /* Fetch rune and mode for current glyph. */
1214                 rune = glyphs[i].u;
1215                 mode = glyphs[i].mode;
1216
1217                 /* Skip dummy wide-character spacing. */
1218                 if (mode == ATTR_WDUMMY)
1219                         continue;
1220
1221                 /* Determine font for glyph if different from previous glyph. */
1222                 if (prevmode != mode) {
1223                         prevmode = mode;
1224                         font = &dc.font;
1225                         frcflags = FRC_NORMAL;
1226                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1227                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1228                                 font = &dc.ibfont;
1229                                 frcflags = FRC_ITALICBOLD;
1230                         } else if (mode & ATTR_ITALIC) {
1231                                 font = &dc.ifont;
1232                                 frcflags = FRC_ITALIC;
1233                         } else if (mode & ATTR_BOLD) {
1234                                 font = &dc.bfont;
1235                                 frcflags = FRC_BOLD;
1236                         }
1237                         yp = winy + font->ascent;
1238                 }
1239
1240                 /* Lookup character index with default font. */
1241                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1242                 if (glyphidx) {
1243                         specs[numspecs].font = font->match;
1244                         specs[numspecs].glyph = glyphidx;
1245                         specs[numspecs].x = (short)xp;
1246                         specs[numspecs].y = (short)yp;
1247                         xp += runewidth;
1248                         numspecs++;
1249                         continue;
1250                 }
1251
1252                 /* Fallback on font cache, search the font cache for match. */
1253                 for (f = 0; f < frclen; f++) {
1254                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1255                         /* Everything correct. */
1256                         if (glyphidx && frc[f].flags == frcflags)
1257                                 break;
1258                         /* We got a default font for a not found glyph. */
1259                         if (!glyphidx && frc[f].flags == frcflags
1260                                         && frc[f].unicodep == rune) {
1261                                 break;
1262                         }
1263                 }
1264
1265                 /* Nothing was found. Use fontconfig to find matching font. */
1266                 if (f >= frclen) {
1267                         if (!font->set)
1268                                 font->set = FcFontSort(0, font->pattern,
1269                                                        1, 0, &fcres);
1270                         fcsets[0] = font->set;
1271
1272                         /*
1273                          * Nothing was found in the cache. Now use
1274                          * some dozen of Fontconfig calls to get the
1275                          * font for one single character.
1276                          *
1277                          * Xft and fontconfig are design failures.
1278                          */
1279                         fcpattern = FcPatternDuplicate(font->pattern);
1280                         fccharset = FcCharSetCreate();
1281
1282                         FcCharSetAddChar(fccharset, rune);
1283                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1284                                         fccharset);
1285                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1286
1287                         FcConfigSubstitute(0, fcpattern,
1288                                         FcMatchPattern);
1289                         FcDefaultSubstitute(fcpattern);
1290
1291                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1292                                         fcpattern, &fcres);
1293
1294                         /* Allocate memory for the new cache entry. */
1295                         if (frclen >= frccap) {
1296                                 frccap += 16;
1297                                 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1298                         }
1299
1300                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1301                                         fontpattern);
1302                         if (!frc[frclen].font)
1303                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1304                                         strerror(errno));
1305                         frc[frclen].flags = frcflags;
1306                         frc[frclen].unicodep = rune;
1307
1308                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1309
1310                         f = frclen;
1311                         frclen++;
1312
1313                         FcPatternDestroy(fcpattern);
1314                         FcCharSetDestroy(fccharset);
1315                 }
1316
1317                 specs[numspecs].font = frc[f].font;
1318                 specs[numspecs].glyph = glyphidx;
1319                 specs[numspecs].x = (short)xp;
1320                 specs[numspecs].y = (short)yp;
1321                 xp += runewidth;
1322                 numspecs++;
1323         }
1324
1325         return numspecs;
1326 }
1327
1328 void
1329 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1330 {
1331         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1332         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1333             width = charlen * win.cw;
1334         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1335         XRenderColor colfg, colbg;
1336         XRectangle r;
1337
1338         /* Fallback on color display for attributes not supported by the font */
1339         if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1340                 if (dc.ibfont.badslant || dc.ibfont.badweight)
1341                         base.fg = defaultattr;
1342         } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1343             (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1344                 base.fg = defaultattr;
1345         }
1346
1347         if (IS_TRUECOL(base.fg)) {
1348                 colfg.alpha = 0xffff;
1349                 colfg.red = TRUERED(base.fg);
1350                 colfg.green = TRUEGREEN(base.fg);
1351                 colfg.blue = TRUEBLUE(base.fg);
1352                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1353                 fg = &truefg;
1354         } else {
1355                 fg = &dc.col[base.fg];
1356         }
1357
1358         if (IS_TRUECOL(base.bg)) {
1359                 colbg.alpha = 0xffff;
1360                 colbg.green = TRUEGREEN(base.bg);
1361                 colbg.red = TRUERED(base.bg);
1362                 colbg.blue = TRUEBLUE(base.bg);
1363                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1364                 bg = &truebg;
1365         } else {
1366                 bg = &dc.col[base.bg];
1367         }
1368
1369         /* Change basic system colors [0-7] to bright system colors [8-15] */
1370         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1371                 fg = &dc.col[base.fg + 8];
1372
1373         if (IS_SET(MODE_REVERSE)) {
1374                 if (fg == &dc.col[defaultfg]) {
1375                         fg = &dc.col[defaultbg];
1376                 } else {
1377                         colfg.red = ~fg->color.red;
1378                         colfg.green = ~fg->color.green;
1379                         colfg.blue = ~fg->color.blue;
1380                         colfg.alpha = fg->color.alpha;
1381                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1382                                         &revfg);
1383                         fg = &revfg;
1384                 }
1385
1386                 if (bg == &dc.col[defaultbg]) {
1387                         bg = &dc.col[defaultfg];
1388                 } else {
1389                         colbg.red = ~bg->color.red;
1390                         colbg.green = ~bg->color.green;
1391                         colbg.blue = ~bg->color.blue;
1392                         colbg.alpha = bg->color.alpha;
1393                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1394                                         &revbg);
1395                         bg = &revbg;
1396                 }
1397         }
1398
1399         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1400                 colfg.red = fg->color.red / 2;
1401                 colfg.green = fg->color.green / 2;
1402                 colfg.blue = fg->color.blue / 2;
1403                 colfg.alpha = fg->color.alpha;
1404                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1405                 fg = &revfg;
1406         }
1407
1408         if (base.mode & ATTR_REVERSE) {
1409                 temp = fg;
1410                 fg = bg;
1411                 bg = temp;
1412         }
1413
1414         if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1415                 fg = bg;
1416
1417         if (base.mode & ATTR_INVISIBLE)
1418                 fg = bg;
1419
1420         /* Intelligent cleaning up of the borders. */
1421         if (x == 0) {
1422                 xclear(0, (y == 0)? 0 : winy, borderpx,
1423                         winy + win.ch +
1424                         ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1425         }
1426         if (winx + width >= borderpx + win.tw) {
1427                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1428                         ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1429         }
1430         if (y == 0)
1431                 xclear(winx, 0, winx + width, borderpx);
1432         if (winy + win.ch >= borderpx + win.th)
1433                 xclear(winx, winy + win.ch, winx + width, win.h);
1434
1435         /* Clean up the region we want to draw to. */
1436         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1437
1438         /* Set the clip region because Xft is sometimes dirty. */
1439         r.x = 0;
1440         r.y = 0;
1441         r.height = win.ch;
1442         r.width = width;
1443         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1444
1445         /* Render the glyphs. */
1446         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1447
1448         /* Render underline and strikethrough. */
1449         if (base.mode & ATTR_UNDERLINE) {
1450                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1451                                 width, 1);
1452         }
1453
1454         if (base.mode & ATTR_STRUCK) {
1455                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1456                                 width, 1);
1457         }
1458
1459         /* Reset clip to none. */
1460         XftDrawSetClip(xw.draw, 0);
1461 }
1462
1463 void
1464 xdrawglyph(Glyph g, int x, int y)
1465 {
1466         int numspecs;
1467         XftGlyphFontSpec spec;
1468
1469         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1470         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1471 }
1472
1473 void
1474 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1475 {
1476         Color drawcol;
1477
1478         /* remove the old cursor */
1479         if (selected(ox, oy))
1480                 og.mode ^= ATTR_REVERSE;
1481         xdrawglyph(og, ox, oy);
1482
1483         if (IS_SET(MODE_HIDE))
1484                 return;
1485
1486         /*
1487          * Select the right color for the right mode.
1488          */
1489         g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1490
1491         if (IS_SET(MODE_REVERSE)) {
1492                 g.mode |= ATTR_REVERSE;
1493                 g.bg = defaultfg;
1494                 if (selected(cx, cy)) {
1495                         drawcol = dc.col[defaultcs];
1496                         g.fg = defaultrcs;
1497                 } else {
1498                         drawcol = dc.col[defaultrcs];
1499                         g.fg = defaultcs;
1500                 }
1501         } else {
1502                 if (selected(cx, cy)) {
1503                         g.fg = defaultfg;
1504                         g.bg = defaultrcs;
1505                 } else {
1506                         g.fg = defaultbg;
1507                         g.bg = defaultcs;
1508                 }
1509                 drawcol = dc.col[g.bg];
1510         }
1511
1512         /* draw the new one */
1513         if (IS_SET(MODE_FOCUSED)) {
1514                 switch (win.cursor) {
1515                 case 7: /* st extension: snowman (U+2603) */
1516                         g.u = 0x2603;
1517                 case 0: /* Blinking Block */
1518                 case 1: /* Blinking Block (Default) */
1519                 case 2: /* Steady Block */
1520                         xdrawglyph(g, cx, cy);
1521                         break;
1522                 case 3: /* Blinking Underline */
1523                 case 4: /* Steady Underline */
1524                         XftDrawRect(xw.draw, &drawcol,
1525                                         borderpx + cx * win.cw,
1526                                         borderpx + (cy + 1) * win.ch - \
1527                                                 cursorthickness,
1528                                         win.cw, cursorthickness);
1529                         break;
1530                 case 5: /* Blinking bar */
1531                 case 6: /* Steady bar */
1532                         XftDrawRect(xw.draw, &drawcol,
1533                                         borderpx + cx * win.cw,
1534                                         borderpx + cy * win.ch,
1535                                         cursorthickness, win.ch);
1536                         break;
1537                 }
1538         } else {
1539                 XftDrawRect(xw.draw, &drawcol,
1540                                 borderpx + cx * win.cw,
1541                                 borderpx + cy * win.ch,
1542                                 win.cw - 1, 1);
1543                 XftDrawRect(xw.draw, &drawcol,
1544                                 borderpx + cx * win.cw,
1545                                 borderpx + cy * win.ch,
1546                                 1, win.ch - 1);
1547                 XftDrawRect(xw.draw, &drawcol,
1548                                 borderpx + (cx + 1) * win.cw - 1,
1549                                 borderpx + cy * win.ch,
1550                                 1, win.ch - 1);
1551                 XftDrawRect(xw.draw, &drawcol,
1552                                 borderpx + cx * win.cw,
1553                                 borderpx + (cy + 1) * win.ch - 1,
1554                                 win.cw, 1);
1555         }
1556 }
1557
1558 void
1559 xsetenv(void)
1560 {
1561         char buf[sizeof(long) * 8 + 1];
1562
1563         snprintf(buf, sizeof(buf), "%lu", xw.win);
1564         setenv("WINDOWID", buf, 1);
1565 }
1566
1567 void
1568 xsettitle(char *p)
1569 {
1570         XTextProperty prop;
1571         DEFAULT(p, opt_title);
1572
1573         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1574                         &prop);
1575         XSetWMName(xw.dpy, xw.win, &prop);
1576         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1577         XFree(prop.value);
1578 }
1579
1580 int
1581 xstartdraw(void)
1582 {
1583         return IS_SET(MODE_VISIBLE);
1584 }
1585
1586 void
1587 xdrawline(Line line, int x1, int y1, int x2)
1588 {
1589         int i, x, ox, numspecs;
1590         Glyph base, new;
1591         XftGlyphFontSpec *specs = xw.specbuf;
1592
1593         numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1594         i = ox = 0;
1595         for (x = x1; x < x2 && i < numspecs; x++) {
1596                 new = line[x];
1597                 if (new.mode == ATTR_WDUMMY)
1598                         continue;
1599                 if (selected(x, y1))
1600                         new.mode ^= ATTR_REVERSE;
1601                 if (i > 0 && ATTRCMP(base, new)) {
1602                         xdrawglyphfontspecs(specs, base, i, ox, y1);
1603                         specs += i;
1604                         numspecs -= i;
1605                         i = 0;
1606                 }
1607                 if (i == 0) {
1608                         ox = x;
1609                         base = new;
1610                 }
1611                 i++;
1612         }
1613         if (i > 0)
1614                 xdrawglyphfontspecs(specs, base, i, ox, y1);
1615 }
1616
1617 void
1618 xfinishdraw(void)
1619 {
1620         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1621                         win.h, 0, 0);
1622         XSetForeground(xw.dpy, dc.gc,
1623                         dc.col[IS_SET(MODE_REVERSE)?
1624                                 defaultfg : defaultbg].pixel);
1625 }
1626
1627 void
1628 xximspot(int x, int y)
1629 {
1630         if (xw.ime.xic == NULL)
1631                 return;
1632
1633         xw.ime.spot.x = borderpx + x * win.cw;
1634         xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1635
1636         XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1637 }
1638
1639 void
1640 expose(XEvent *ev)
1641 {
1642         redraw();
1643 }
1644
1645 void
1646 visibility(XEvent *ev)
1647 {
1648         XVisibilityEvent *e = &ev->xvisibility;
1649
1650         MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1651 }
1652
1653 void
1654 unmap(XEvent *ev)
1655 {
1656         win.mode &= ~MODE_VISIBLE;
1657 }
1658
1659 void
1660 xsetpointermotion(int set)
1661 {
1662         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1663         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1664 }
1665
1666 void
1667 xsetmode(int set, unsigned int flags)
1668 {
1669         int mode = win.mode;
1670         MODBIT(win.mode, set, flags);
1671         if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1672                 redraw();
1673 }
1674
1675 int
1676 xsetcursor(int cursor)
1677 {
1678         DEFAULT(cursor, 1);
1679         if (!BETWEEN(cursor, 0, 6))
1680                 return 1;
1681         win.cursor = cursor;
1682         return 0;
1683 }
1684
1685 void
1686 xseturgency(int add)
1687 {
1688         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1689
1690         MODBIT(h->flags, add, XUrgencyHint);
1691         XSetWMHints(xw.dpy, xw.win, h);
1692         XFree(h);
1693 }
1694
1695 void
1696 xbell(void)
1697 {
1698         if (!(IS_SET(MODE_FOCUSED)))
1699                 xseturgency(1);
1700         if (bellvolume)
1701                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1702 }
1703
1704 void
1705 focus(XEvent *ev)
1706 {
1707         XFocusChangeEvent *e = &ev->xfocus;
1708
1709         if (e->mode == NotifyGrab)
1710                 return;
1711
1712         if (ev->type == FocusIn) {
1713                 if (xw.ime.xic)
1714                         XSetICFocus(xw.ime.xic);
1715                 win.mode |= MODE_FOCUSED;
1716                 xseturgency(0);
1717                 if (IS_SET(MODE_FOCUS))
1718                         ttywrite("\033[I", 3, 0);
1719         } else {
1720                 if (xw.ime.xic)
1721                         XUnsetICFocus(xw.ime.xic);
1722                 win.mode &= ~MODE_FOCUSED;
1723                 if (IS_SET(MODE_FOCUS))
1724                         ttywrite("\033[O", 3, 0);
1725         }
1726 }
1727
1728 int
1729 match(uint mask, uint state)
1730 {
1731         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1732 }
1733
1734 char*
1735 kmap(KeySym k, uint state)
1736 {
1737         Key *kp;
1738         int i;
1739
1740         /* Check for mapped keys out of X11 function keys. */
1741         for (i = 0; i < LEN(mappedkeys); i++) {
1742                 if (mappedkeys[i] == k)
1743                         break;
1744         }
1745         if (i == LEN(mappedkeys)) {
1746                 if ((k & 0xFFFF) < 0xFD00)
1747                         return NULL;
1748         }
1749
1750         for (kp = key; kp < key + LEN(key); kp++) {
1751                 if (kp->k != k)
1752                         continue;
1753
1754                 if (!match(kp->mask, state))
1755                         continue;
1756
1757                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1758                         continue;
1759                 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1760                         continue;
1761
1762                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1763                         continue;
1764
1765                 return kp->s;
1766         }
1767
1768         return NULL;
1769 }
1770
1771 void
1772 kpress(XEvent *ev)
1773 {
1774         XKeyEvent *e = &ev->xkey;
1775         KeySym ksym;
1776         char buf[64], *customkey;
1777         int len;
1778         Rune c;
1779         Status status;
1780         Shortcut *bp;
1781
1782         if (IS_SET(MODE_KBDLOCK))
1783                 return;
1784
1785         if (xw.ime.xic)
1786                 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1787         else
1788                 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1789         /* 1. shortcuts */
1790         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1791                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1792                         bp->func(&(bp->arg));
1793                         return;
1794                 }
1795         }
1796
1797         /* 2. custom keys from config.h */
1798         if ((customkey = kmap(ksym, e->state))) {
1799                 ttywrite(customkey, strlen(customkey), 1);
1800                 return;
1801         }
1802
1803         /* 3. composed string from input method */
1804         if (len == 0)
1805                 return;
1806         if (len == 1 && e->state & Mod1Mask) {
1807                 if (IS_SET(MODE_8BIT)) {
1808                         if (*buf < 0177) {
1809                                 c = *buf | 0x80;
1810                                 len = utf8encode(c, buf);
1811                         }
1812                 } else {
1813                         buf[1] = buf[0];
1814                         buf[0] = '\033';
1815                         len = 2;
1816                 }
1817         }
1818         ttywrite(buf, len, 1);
1819 }
1820
1821 void
1822 cmessage(XEvent *e)
1823 {
1824         /*
1825          * See xembed specs
1826          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1827          */
1828         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1829                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1830                         win.mode |= MODE_FOCUSED;
1831                         xseturgency(0);
1832                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1833                         win.mode &= ~MODE_FOCUSED;
1834                 }
1835         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1836                 ttyhangup();
1837                 exit(0);
1838         }
1839 }
1840
1841 void
1842 resize(XEvent *e)
1843 {
1844         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1845                 return;
1846
1847         cresize(e->xconfigure.width, e->xconfigure.height);
1848 }
1849
1850 void
1851 run(void)
1852 {
1853         XEvent ev;
1854         int w = win.w, h = win.h;
1855         fd_set rfd;
1856         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1857         int ttyfd;
1858         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1859         long deltatime;
1860
1861         /* Waiting for window mapping */
1862         do {
1863                 XNextEvent(xw.dpy, &ev);
1864                 /*
1865                  * This XFilterEvent call is required because of XOpenIM. It
1866                  * does filter out the key event and some client message for
1867                  * the input method too.
1868                  */
1869                 if (XFilterEvent(&ev, None))
1870                         continue;
1871                 if (ev.type == ConfigureNotify) {
1872                         w = ev.xconfigure.width;
1873                         h = ev.xconfigure.height;
1874                 }
1875         } while (ev.type != MapNotify);
1876
1877         ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1878         cresize(w, h);
1879
1880         clock_gettime(CLOCK_MONOTONIC, &last);
1881         lastblink = last;
1882
1883         for (xev = actionfps;;) {
1884                 FD_ZERO(&rfd);
1885                 FD_SET(ttyfd, &rfd);
1886                 FD_SET(xfd, &rfd);
1887
1888                 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1889                         if (errno == EINTR)
1890                                 continue;
1891                         die("select failed: %s\n", strerror(errno));
1892                 }
1893                 if (FD_ISSET(ttyfd, &rfd)) {
1894                         ttyread();
1895                         if (blinktimeout) {
1896                                 blinkset = tattrset(ATTR_BLINK);
1897                                 if (!blinkset)
1898                                         MODBIT(win.mode, 0, MODE_BLINK);
1899                         }
1900                 }
1901
1902                 if (FD_ISSET(xfd, &rfd))
1903                         xev = actionfps;
1904
1905                 clock_gettime(CLOCK_MONOTONIC, &now);
1906                 drawtimeout.tv_sec = 0;
1907                 drawtimeout.tv_nsec =  (1000 * 1E6)/ xfps;
1908                 tv = &drawtimeout;
1909
1910                 dodraw = 0;
1911                 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1912                         tsetdirtattr(ATTR_BLINK);
1913                         win.mode ^= MODE_BLINK;
1914                         lastblink = now;
1915                         dodraw = 1;
1916                 }
1917                 deltatime = TIMEDIFF(now, last);
1918                 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1919                         dodraw = 1;
1920                         last = now;
1921                 }
1922
1923                 if (dodraw) {
1924                         while (XPending(xw.dpy)) {
1925                                 XNextEvent(xw.dpy, &ev);
1926                                 if (XFilterEvent(&ev, None))
1927                                         continue;
1928                                 if (handler[ev.type])
1929                                         (handler[ev.type])(&ev);
1930                         }
1931
1932                         draw();
1933                         XFlush(xw.dpy);
1934
1935                         if (xev && !FD_ISSET(xfd, &rfd))
1936                                 xev--;
1937                         if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1938                                 if (blinkset) {
1939                                         if (TIMEDIFF(now, lastblink) \
1940                                                         > blinktimeout) {
1941                                                 drawtimeout.tv_nsec = 1000;
1942                                         } else {
1943                                                 drawtimeout.tv_nsec = (1E6 * \
1944                                                         (blinktimeout - \
1945                                                         TIMEDIFF(now,
1946                                                                 lastblink)));
1947                                         }
1948                                         drawtimeout.tv_sec = \
1949                                             drawtimeout.tv_nsec / 1E9;
1950                                         drawtimeout.tv_nsec %= (long)1E9;
1951                                 } else {
1952                                         tv = NULL;
1953                                 }
1954                         }
1955                 }
1956         }
1957 }
1958
1959 void
1960 usage(void)
1961 {
1962         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1963             " [-n name] [-o file]\n"
1964             "          [-T title] [-t title] [-w windowid]"
1965             " [[-e] command [args ...]]\n"
1966             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
1967             " [-n name] [-o file]\n"
1968             "          [-T title] [-t title] [-w windowid] -l line"
1969             " [stty_args ...]\n", argv0, argv0);
1970 }
1971
1972 int
1973 main(int argc, char *argv[])
1974 {
1975         xw.l = xw.t = 0;
1976         xw.isfixed = False;
1977         win.cursor = cursorshape;
1978
1979         ARGBEGIN {
1980         case 'a':
1981                 allowaltscreen = 0;
1982                 break;
1983         case 'c':
1984                 opt_class = EARGF(usage());
1985                 break;
1986         case 'e':
1987                 if (argc > 0)
1988                         --argc, ++argv;
1989                 goto run;
1990         case 'f':
1991                 opt_font = EARGF(usage());
1992                 break;
1993         case 'g':
1994                 xw.gm = XParseGeometry(EARGF(usage()),
1995                                 &xw.l, &xw.t, &cols, &rows);
1996                 break;
1997         case 'i':
1998                 xw.isfixed = 1;
1999                 break;
2000         case 'o':
2001                 opt_io = EARGF(usage());
2002                 break;
2003         case 'l':
2004                 opt_line = EARGF(usage());
2005                 break;
2006         case 'n':
2007                 opt_name = EARGF(usage());
2008                 break;
2009         case 't':
2010         case 'T':
2011                 opt_title = EARGF(usage());
2012                 break;
2013         case 'w':
2014                 opt_embed = EARGF(usage());
2015                 break;
2016         case 'v':
2017                 die("%s " VERSION "\n", argv0);
2018                 break;
2019         default:
2020                 usage();
2021         } ARGEND;
2022
2023 run:
2024         if (argc > 0) /* eat all remaining arguments */
2025                 opt_cmd = argv;
2026
2027         if (!opt_title)
2028                 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2029
2030         setlocale(LC_CTYPE, "");
2031         XSetLocaleModifiers("");
2032         cols = MAX(cols, 1);
2033         rows = MAX(rows, 1);
2034         tnew(cols, rows);
2035         xinit(cols, rows);
2036         xsetenv();
2037         selinit();
2038         run();
2039
2040         return 0;
2041 }