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