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