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