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