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