first
[dcc-suckless-config] / based-simple-term / 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 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         int  altscrn;  /* 0: don't care, -1: not alt screen, 1: alt screen */
38 } MouseShortcut;
39
40 typedef struct {
41         KeySym k;
42         uint mask;
43         char *s;
44         /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
45         signed char appkey;    /* application keypad */
46         signed char appcursor; /* application cursor */
47 } Key;
48
49 /* Undercurl slope types */
50 enum undercurl_slope_type {
51         UNDERCURL_SLOPE_ASCENDING = 0,
52         UNDERCURL_SLOPE_TOP_CAP = 1,
53         UNDERCURL_SLOPE_DESCENDING = 2,
54         UNDERCURL_SLOPE_BOTTOM_CAP = 3
55 };
56
57 /* X modifiers */
58 #define XK_ANY_MOD    UINT_MAX
59 #define XK_NO_MOD     0
60 #define XK_SWITCH_MOD (1<<13|1<<14)
61
62 /* function definitions used in config.h */
63 static void clipcopy(const Arg *);
64 static void clippaste(const Arg *);
65 static void numlock(const Arg *);
66 static void selpaste(const Arg *);
67 static void zoom(const Arg *);
68 static void zoomabs(const Arg *);
69 static void zoomreset(const Arg *);
70 static void ttysend(const Arg *);
71
72 /* config.h for applying patches and the configuration. */
73 #include "config.h"
74
75 /* XEMBED messages */
76 #define XEMBED_FOCUS_IN  4
77 #define XEMBED_FOCUS_OUT 5
78
79 /* macros */
80 #define IS_SET(flag)            ((win.mode & (flag)) != 0)
81 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
82 #define TRUEGREEN(x)            (((x) & 0xff00))
83 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
84
85 typedef XftDraw *Draw;
86 typedef XftColor Color;
87 typedef XftGlyphFontSpec GlyphFontSpec;
88
89 /* Purely graphic info */
90 typedef struct {
91         int tw, th; /* tty width and height */
92         int w, h; /* window width and height */
93         int ch; /* char height */
94         int cw; /* char width  */
95         int mode; /* window state/mode flags */
96         int cursor; /* cursor style */
97 } TermWindow;
98
99 typedef struct {
100         Display *dpy;
101         Colormap cmap;
102         Window win;
103         Drawable buf;
104         GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
105         Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
106         struct {
107                 XIM xim;
108                 XIC xic;
109                 XPoint spot;
110                 XVaNestedList spotlist;
111         } ime;
112         Draw draw;
113         Visual *vis;
114         XSetWindowAttributes attrs;
115         int scr;
116         int isfixed; /* is fixed geometry? */
117         int depth; /* bit depth */
118         int l, t; /* left and top offset */
119         int gm; /* geometry mask */
120 } XWindow;
121
122 typedef struct {
123         Atom xtarget;
124         char *primary, *clipboard;
125         struct timespec tclick1;
126         struct timespec tclick2;
127 } XSelection;
128
129 /* Font structure */
130 #define Font Font_
131 typedef struct {
132         int height;
133         int width;
134         int ascent;
135         int descent;
136         int badslant;
137         int badweight;
138         short lbearing;
139         short rbearing;
140         XftFont *match;
141         FcFontSet *set;
142         FcPattern *pattern;
143 } Font;
144
145 /* Drawing Context */
146 typedef struct {
147         Color *col;
148         size_t collen;
149         Font font, bfont, ifont, ibfont;
150         GC gc;
151 } DC;
152
153 static inline ushort sixd_to_16bit(int);
154 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
155 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
156 static void xdrawglyph(Glyph, int, int);
157 static void xclear(int, int, int, int);
158 static int xgeommasktogravity(int);
159 static int ximopen(Display *);
160 static void ximinstantiate(Display *, XPointer, XPointer);
161 static void ximdestroy(XIM, XPointer, XPointer);
162 static int xicdestroy(XIC, XPointer, XPointer);
163 static void xinit(int, int);
164 static void cresize(int, int);
165 static void xresize(int, int);
166 static void xhints(void);
167 static int xloadcolor(int, const char *, Color *);
168 static int xloadfont(Font *, FcPattern *);
169 static void xloadfonts(const char *, double);
170 static void xunloadfont(Font *);
171 static void xunloadfonts(void);
172 static void xsetenv(void);
173 static void xseturgency(int);
174 static int evcol(XEvent *);
175 static int evrow(XEvent *);
176
177 static void expose(XEvent *);
178 static void visibility(XEvent *);
179 static void unmap(XEvent *);
180 static void kpress(XEvent *);
181 static void cmessage(XEvent *);
182 static void resize(XEvent *);
183 static void focus(XEvent *);
184 static uint buttonmask(uint);
185 static int mouseaction(XEvent *, uint);
186 static void brelease(XEvent *);
187 static void bpress(XEvent *);
188 static void bmotion(XEvent *);
189 static void propnotify(XEvent *);
190 static void selnotify(XEvent *);
191 static void selclear_(XEvent *);
192 static void selrequest(XEvent *);
193 static void setsel(char *, Time);
194 static void mousesel(XEvent *, int);
195 static void mousereport(XEvent *);
196 static char *kmap(KeySym, uint);
197 static int match(uint, uint);
198
199 static void run(void);
200 static void usage(void);
201
202 static void (*handler[LASTEvent])(XEvent *) = {
203         [KeyPress] = kpress,
204         [ClientMessage] = cmessage,
205         [ConfigureNotify] = resize,
206         [VisibilityNotify] = visibility,
207         [UnmapNotify] = unmap,
208         [Expose] = expose,
209         [FocusIn] = focus,
210         [FocusOut] = focus,
211         [MotionNotify] = bmotion,
212         [ButtonPress] = bpress,
213         [ButtonRelease] = brelease,
214 /*
215  * Uncomment if you want the selection to disappear when you select something
216  * different in another window.
217  */
218 /*      [SelectionClear] = selclear_, */
219         [SelectionNotify] = selnotify,
220 /*
221  * PropertyNotify is only turned on when there is some INCR transfer happening
222  * for the selection retrieval.
223  */
224         [PropertyNotify] = propnotify,
225         [SelectionRequest] = selrequest,
226 };
227
228 /* Globals */
229 static DC dc;
230 static XWindow xw;
231 static XSelection xsel;
232 static TermWindow win;
233
234 /* Font Ring Cache */
235 enum {
236         FRC_NORMAL,
237         FRC_ITALIC,
238         FRC_BOLD,
239         FRC_ITALICBOLD
240 };
241
242 typedef struct {
243         XftFont *font;
244         int flags;
245         Rune unicodep;
246 } Fontcache;
247
248 /* Fontcache is an array now. A new font will be appended to the array. */
249 static Fontcache *frc = NULL;
250 static int frclen = 0;
251 static int frccap = 0;
252 static char *usedfont = NULL;
253 static double usedfontsize = 0;
254 static double defaultfontsize = 0;
255
256 static char *opt_alpha = NULL;
257 static char *opt_class = NULL;
258 static char **opt_cmd  = NULL;
259 static char *opt_embed = NULL;
260 static char *opt_font  = NULL;
261 static char *opt_io    = NULL;
262 static char *opt_line  = NULL;
263 static char *opt_name  = NULL;
264 static char *opt_title = NULL;
265
266 static uint buttons; /* bit field of pressed buttons */
267
268 void
269 clipcopy(const Arg *dummy)
270 {
271         Atom clipboard;
272
273         free(xsel.clipboard);
274         xsel.clipboard = NULL;
275
276         if (xsel.primary != NULL) {
277                 xsel.clipboard = xstrdup(xsel.primary);
278                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
279                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
280         }
281 }
282
283 void
284 clippaste(const Arg *dummy)
285 {
286         Atom clipboard;
287
288         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
289         XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
290                         xw.win, CurrentTime);
291 }
292
293 void
294 selpaste(const Arg *dummy)
295 {
296         XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
297                         xw.win, CurrentTime);
298 }
299
300 void
301 numlock(const Arg *dummy)
302 {
303         win.mode ^= MODE_NUMLOCK;
304 }
305
306 void
307 zoom(const Arg *arg)
308 {
309         Arg larg;
310
311         larg.f = usedfontsize + arg->f;
312         zoomabs(&larg);
313 }
314
315 void
316 zoomabs(const Arg *arg)
317 {
318         xunloadfonts();
319         xloadfonts(usedfont, arg->f);
320         cresize(0, 0);
321         redraw();
322         xhints();
323 }
324
325 void
326 zoomreset(const Arg *arg)
327 {
328         Arg larg;
329
330         if (defaultfontsize > 0) {
331                 larg.f = defaultfontsize;
332                 zoomabs(&larg);
333         }
334 }
335
336 void
337 ttysend(const Arg *arg)
338 {
339         ttywrite(arg->s, strlen(arg->s), 1);
340 }
341
342 int
343 evcol(XEvent *e)
344 {
345         int x = e->xbutton.x - borderpx;
346         LIMIT(x, 0, win.tw - 1);
347         return x / win.cw;
348 }
349
350 int
351 evrow(XEvent *e)
352 {
353         int y = e->xbutton.y - borderpx;
354         LIMIT(y, 0, win.th - 1);
355         return y / win.ch;
356 }
357
358 void
359 mousesel(XEvent *e, int done)
360 {
361         int type, seltype = SEL_REGULAR;
362         uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
363
364         for (type = 1; type < LEN(selmasks); ++type) {
365                 if (match(selmasks[type], state)) {
366                         seltype = type;
367                         break;
368                 }
369         }
370         selextend(evcol(e), evrow(e), seltype, done);
371         if (done)
372                 setsel(getsel(), e->xbutton.time);
373 }
374
375 void
376 mousereport(XEvent *e)
377 {
378         int len, btn, code;
379         int x = evcol(e), y = evrow(e);
380         int state = e->xbutton.state;
381         char buf[40];
382         static int ox, oy;
383
384         if (e->type == MotionNotify) {
385                 if (x == ox && y == oy)
386                         return;
387                 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
388                         return;
389                 /* MODE_MOUSEMOTION: no reporting if no button is pressed */
390                 if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
391                         return;
392                 /* Set btn to lowest-numbered pressed button, or 12 if no
393                  * buttons are pressed. */
394                 for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++)
395                         ;
396                 code = 32;
397         } else {
398                 btn = e->xbutton.button;
399                 /* Only buttons 1 through 11 can be encoded */
400                 if (btn < 1 || btn > 11)
401                         return;
402                 if (e->type == ButtonRelease) {
403                         /* MODE_MOUSEX10: no button release reporting */
404                         if (IS_SET(MODE_MOUSEX10))
405                                 return;
406                         /* Don't send release events for the scroll wheel */
407                         if (btn == 4 || btn == 5)
408                                 return;
409                 }
410                 code = 0;
411         }
412
413         ox = x;
414         oy = y;
415
416         /* Encode btn into code. If no button is pressed for a motion event in
417          * MODE_MOUSEMANY, then encode it as a release. */
418         if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12)
419                 code += 3;
420         else if (btn >= 8)
421                 code += 128 + btn - 8;
422         else if (btn >= 4)
423                 code += 64 + btn - 4;
424         else
425                 code += btn - 1;
426
427         if (!IS_SET(MODE_MOUSEX10)) {
428                 code += ((state & ShiftMask  ) ?  4 : 0)
429                       + ((state & Mod1Mask   ) ?  8 : 0) /* meta key: alt */
430                       + ((state & ControlMask) ? 16 : 0);
431         }
432
433         if (IS_SET(MODE_MOUSESGR)) {
434                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
435                                 code, x+1, y+1,
436                                 e->type == ButtonRelease ? 'm' : 'M');
437         } else if (x < 223 && y < 223) {
438                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
439                                 32+code, 32+x+1, 32+y+1);
440         } else {
441                 return;
442         }
443
444         ttywrite(buf, len, 0);
445 }
446
447 uint
448 buttonmask(uint button)
449 {
450         return button == Button1 ? Button1Mask
451              : button == Button2 ? Button2Mask
452              : button == Button3 ? Button3Mask
453              : button == Button4 ? Button4Mask
454              : button == Button5 ? Button5Mask
455              : 0;
456 }
457
458 int
459 mouseaction(XEvent *e, uint release)
460 {
461         MouseShortcut *ms;
462
463         /* ignore Button<N>mask for Button<N> - it's set on release */
464         uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
465
466         for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
467                 if (ms->release == release &&
468                     ms->button == e->xbutton.button &&
469                     (!ms->altscrn || (ms->altscrn == (tisaltscr() ? 1 : -1))) &&
470                     (match(ms->mod, state) ||  /* exact or forced */
471                      match(ms->mod, state & ~forcemousemod))) {
472                         ms->func(&(ms->arg));
473                         return 1;
474                 }
475         }
476
477         return 0;
478 }
479
480 void
481 bpress(XEvent *e)
482 {
483         int btn = e->xbutton.button;
484         struct timespec now;
485         int snap;
486
487         if (1 <= btn && btn <= 11)
488                 buttons |= 1 << (btn-1);
489
490         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
491                 mousereport(e);
492                 return;
493         }
494
495         if (mouseaction(e, 0))
496                 return;
497
498         if (btn == Button1) {
499                 /*
500                  * If the user clicks below predefined timeouts specific
501                  * snapping behaviour is exposed.
502                  */
503                 clock_gettime(CLOCK_MONOTONIC, &now);
504                 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
505                         snap = SNAP_LINE;
506                 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
507                         snap = SNAP_WORD;
508                 } else {
509                         snap = 0;
510                 }
511                 xsel.tclick2 = xsel.tclick1;
512                 xsel.tclick1 = now;
513
514                 selstart(evcol(e), evrow(e), snap);
515         }
516 }
517
518 void
519 propnotify(XEvent *e)
520 {
521         XPropertyEvent *xpev;
522         Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
523
524         xpev = &e->xproperty;
525         if (xpev->state == PropertyNewValue &&
526                         (xpev->atom == XA_PRIMARY ||
527                          xpev->atom == clipboard)) {
528                 selnotify(e);
529         }
530 }
531
532 void
533 selnotify(XEvent *e)
534 {
535         ulong nitems, ofs, rem;
536         int format;
537         uchar *data, *last, *repl;
538         Atom type, incratom, property = None;
539
540         incratom = XInternAtom(xw.dpy, "INCR", 0);
541
542         ofs = 0;
543         if (e->type == SelectionNotify)
544                 property = e->xselection.property;
545         else if (e->type == PropertyNotify)
546                 property = e->xproperty.atom;
547
548         if (property == None)
549                 return;
550
551         do {
552                 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
553                                         BUFSIZ/4, False, AnyPropertyType,
554                                         &type, &format, &nitems, &rem,
555                                         &data)) {
556                         fprintf(stderr, "Clipboard allocation failed\n");
557                         return;
558                 }
559
560                 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
561                         /*
562                          * If there is some PropertyNotify with no data, then
563                          * this is the signal of the selection owner that all
564                          * data has been transferred. We won't need to receive
565                          * PropertyNotify events anymore.
566                          */
567                         MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
568                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
569                                         &xw.attrs);
570                 }
571
572                 if (type == incratom) {
573                         /*
574                          * Activate the PropertyNotify events so we receive
575                          * when the selection owner does send us the next
576                          * chunk of data.
577                          */
578                         MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
579                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
580                                         &xw.attrs);
581
582                         /*
583                          * Deleting the property is the transfer start signal.
584                          */
585                         XDeleteProperty(xw.dpy, xw.win, (int)property);
586                         continue;
587                 }
588
589                 /*
590                  * As seen in getsel:
591                  * Line endings are inconsistent in the terminal and GUI world
592                  * copy and pasting. When receiving some selection data,
593                  * replace all '\n' with '\r'.
594                  * FIXME: Fix the computer world.
595                  */
596                 repl = data;
597                 last = data + nitems * format / 8;
598                 while ((repl = memchr(repl, '\n', last - repl))) {
599                         *repl++ = '\r';
600                 }
601
602                 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
603                         ttywrite("\033[200~", 6, 0);
604                 ttywrite((char *)data, nitems * format / 8, 1);
605                 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
606                         ttywrite("\033[201~", 6, 0);
607                 XFree(data);
608                 /* number of 32-bit chunks returned */
609                 ofs += nitems * format / 32;
610         } while (rem > 0);
611
612         /*
613          * Deleting the property again tells the selection owner to send the
614          * next data chunk in the property.
615          */
616         XDeleteProperty(xw.dpy, xw.win, (int)property);
617 }
618
619 void
620 xclipcopy(void)
621 {
622         clipcopy(NULL);
623 }
624
625 void
626 selclear_(XEvent *e)
627 {
628         selclear();
629 }
630
631 void
632 selrequest(XEvent *e)
633 {
634         XSelectionRequestEvent *xsre;
635         XSelectionEvent xev;
636         Atom xa_targets, string, clipboard;
637         char *seltext;
638
639         xsre = (XSelectionRequestEvent *) e;
640         xev.type = SelectionNotify;
641         xev.requestor = xsre->requestor;
642         xev.selection = xsre->selection;
643         xev.target = xsre->target;
644         xev.time = xsre->time;
645         if (xsre->property == None)
646                 xsre->property = xsre->target;
647
648         /* reject */
649         xev.property = None;
650
651         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
652         if (xsre->target == xa_targets) {
653                 /* respond with the supported type */
654                 string = xsel.xtarget;
655                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
656                                 XA_ATOM, 32, PropModeReplace,
657                                 (uchar *) &string, 1);
658                 xev.property = xsre->property;
659         } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
660                 /*
661                  * xith XA_STRING non ascii characters may be incorrect in the
662                  * requestor. It is not our problem, use utf8.
663                  */
664                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
665                 if (xsre->selection == XA_PRIMARY) {
666                         seltext = xsel.primary;
667                 } else if (xsre->selection == clipboard) {
668                         seltext = xsel.clipboard;
669                 } else {
670                         fprintf(stderr,
671                                 "Unhandled clipboard selection 0x%lx\n",
672                                 xsre->selection);
673                         return;
674                 }
675                 if (seltext != NULL) {
676                         XChangeProperty(xsre->display, xsre->requestor,
677                                         xsre->property, xsre->target,
678                                         8, PropModeReplace,
679                                         (uchar *)seltext, strlen(seltext));
680                         xev.property = xsre->property;
681                 }
682         }
683
684         /* all done, send a notification to the listener */
685         if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
686                 fprintf(stderr, "Error sending SelectionNotify event\n");
687 }
688
689 void
690 setsel(char *str, Time t)
691 {
692         if (!str)
693                 return;
694
695         free(xsel.primary);
696         xsel.primary = str;
697
698         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
699         if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
700                 selclear();
701 }
702
703 void
704 xsetsel(char *str)
705 {
706         setsel(str, CurrentTime);
707 }
708
709 void
710 brelease(XEvent *e)
711 {
712         int btn = e->xbutton.button;
713
714         if (1 <= btn && btn <= 11)
715                 buttons &= ~(1 << (btn-1));
716
717         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
718                 mousereport(e);
719                 return;
720         }
721
722         if (mouseaction(e, 1))
723                 return;
724         if (btn == Button1)
725                 mousesel(e, 1);
726 }
727
728 void
729 bmotion(XEvent *e)
730 {
731         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
732                 mousereport(e);
733                 return;
734         }
735
736         mousesel(e, 0);
737 }
738
739 void
740 cresize(int width, int height)
741 {
742         int col, row;
743
744         if (width != 0)
745                 win.w = width;
746         if (height != 0)
747                 win.h = height;
748
749         col = (win.w - 2 * borderpx) / win.cw;
750         row = (win.h - 2 * borderpx) / win.ch;
751         col = MAX(1, col);
752         row = MAX(1, row);
753
754         tresize(col, row);
755         xresize(col, row);
756         ttyresize(win.tw, win.th);
757 }
758
759 void
760 xresize(int col, int row)
761 {
762         win.tw = col * win.cw;
763         win.th = row * win.ch;
764
765         XFreePixmap(xw.dpy, xw.buf);
766         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
767                         xw.depth);
768         XftDrawChange(xw.draw, xw.buf);
769         xclear(0, 0, win.w, win.h);
770
771         /* resize to new width */
772         xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
773 }
774
775 ushort
776 sixd_to_16bit(int x)
777 {
778         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
779 }
780
781 int
782 xloadcolor(int i, const char *name, Color *ncolor)
783 {
784         XRenderColor color = { .alpha = 0xffff };
785
786         if (!name) {
787                 if (BETWEEN(i, 16, 255)) { /* 256 color */
788                         if (i < 6*6*6+16) { /* same colors as xterm */
789                                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
790                                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
791                                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
792                         } else { /* greyscale */
793                                 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
794                                 color.green = color.blue = color.red;
795                         }
796                         return XftColorAllocValue(xw.dpy, xw.vis,
797                                                   xw.cmap, &color, ncolor);
798                 } else
799                         name = colorname[i];
800         }
801
802         return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
803 }
804
805 void
806 xloadcols(void)
807 {
808         int i;
809         static int loaded;
810         Color *cp;
811
812         if (loaded) {
813                 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
814                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
815         } else {
816                 dc.collen = MAX(LEN(colorname), 256);
817                 dc.col = xmalloc(dc.collen * sizeof(Color));
818         }
819
820         for (i = 0; i < dc.collen; i++)
821                 if (!xloadcolor(i, NULL, &dc.col[i])) {
822                         if (colorname[i])
823                                 die("could not allocate color '%s'\n", colorname[i]);
824                         else
825                                 die("could not allocate color %d\n", i);
826                 }
827
828         /* set alpha value of bg color */
829         if (opt_alpha)
830                 alpha = strtof(opt_alpha, NULL);
831         dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
832         dc.col[defaultbg].pixel &= 0x00FFFFFF;
833         dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
834         loaded = 1;
835 }
836
837 int
838 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
839 {
840         if (!BETWEEN(x, 0, dc.collen))
841                 return 1;
842
843         *r = dc.col[x].color.red >> 8;
844         *g = dc.col[x].color.green >> 8;
845         *b = dc.col[x].color.blue >> 8;
846
847         return 0;
848 }
849
850 int
851 xsetcolorname(int x, const char *name)
852 {
853         Color ncolor;
854
855         if (!BETWEEN(x, 0, dc.collen))
856                 return 1;
857
858         if (!xloadcolor(x, name, &ncolor))
859                 return 1;
860
861         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
862         dc.col[x] = ncolor;
863
864         return 0;
865 }
866
867 /*
868  * Absolute coordinates.
869  */
870 void
871 xclear(int x1, int y1, int x2, int y2)
872 {
873         XftDrawRect(xw.draw,
874                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
875                         x1, y1, x2-x1, y2-y1);
876 }
877
878 void
879 xhints(void)
880 {
881         XClassHint class = {opt_name ? opt_name : termname,
882                             opt_class ? opt_class : termname};
883         XWMHints wm = {.flags = InputHint, .input = 1};
884         XSizeHints *sizeh;
885
886         sizeh = XAllocSizeHints();
887
888         sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
889         sizeh->height = win.h;
890         sizeh->width = win.w;
891         sizeh->height_inc = win.ch;
892         sizeh->width_inc = win.cw;
893         sizeh->base_height = 2 * borderpx;
894         sizeh->base_width = 2 * borderpx;
895         sizeh->min_height = win.ch + 2 * borderpx;
896         sizeh->min_width = win.cw + 2 * borderpx;
897         if (xw.isfixed) {
898                 sizeh->flags |= PMaxSize;
899                 sizeh->min_width = sizeh->max_width = win.w;
900                 sizeh->min_height = sizeh->max_height = win.h;
901         }
902         if (xw.gm & (XValue|YValue)) {
903                 sizeh->flags |= USPosition | PWinGravity;
904                 sizeh->x = xw.l;
905                 sizeh->y = xw.t;
906                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
907         }
908
909         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
910                         &class);
911         XFree(sizeh);
912 }
913
914 int
915 xgeommasktogravity(int mask)
916 {
917         switch (mask & (XNegative|YNegative)) {
918         case 0:
919                 return NorthWestGravity;
920         case XNegative:
921                 return NorthEastGravity;
922         case YNegative:
923                 return SouthWestGravity;
924         }
925
926         return SouthEastGravity;
927 }
928
929 int
930 xloadfont(Font *f, FcPattern *pattern)
931 {
932         FcPattern *configured;
933         FcPattern *match;
934         FcResult result;
935         XGlyphInfo extents;
936         int wantattr, haveattr;
937
938         /*
939          * Manually configure instead of calling XftMatchFont
940          * so that we can use the configured pattern for
941          * "missing glyph" lookups.
942          */
943         configured = FcPatternDuplicate(pattern);
944         if (!configured)
945                 return 1;
946
947         FcConfigSubstitute(NULL, configured, FcMatchPattern);
948         XftDefaultSubstitute(xw.dpy, xw.scr, configured);
949
950         match = FcFontMatch(NULL, configured, &result);
951         if (!match) {
952                 FcPatternDestroy(configured);
953                 return 1;
954         }
955
956         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
957                 FcPatternDestroy(configured);
958                 FcPatternDestroy(match);
959                 return 1;
960         }
961
962         if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
963             XftResultMatch)) {
964                 /*
965                  * Check if xft was unable to find a font with the appropriate
966                  * slant but gave us one anyway. Try to mitigate.
967                  */
968                 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
969                     &haveattr) != XftResultMatch) || haveattr < wantattr) {
970                         f->badslant = 1;
971                         fputs("font slant does not match\n", stderr);
972                 }
973         }
974
975         if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
976             XftResultMatch)) {
977                 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
978                     &haveattr) != XftResultMatch) || haveattr != wantattr) {
979                         f->badweight = 1;
980                         fputs("font weight does not match\n", stderr);
981                 }
982         }
983
984         XftTextExtentsUtf8(xw.dpy, f->match,
985                 (const FcChar8 *) ascii_printable,
986                 strlen(ascii_printable), &extents);
987
988         f->set = NULL;
989         f->pattern = configured;
990
991         f->ascent = f->match->ascent;
992         f->descent = f->match->descent;
993         f->lbearing = 0;
994         f->rbearing = f->match->max_advance_width;
995
996         f->height = f->ascent + f->descent;
997         f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
998
999         return 0;
1000 }
1001
1002 void
1003 xloadfonts(const char *fontstr, double fontsize)
1004 {
1005         FcPattern *pattern;
1006         double fontval;
1007
1008         if (fontstr[0] == '-')
1009                 pattern = XftXlfdParse(fontstr, False, False);
1010         else
1011                 pattern = FcNameParse((const FcChar8 *)fontstr);
1012
1013         if (!pattern)
1014                 die("can't open font %s\n", fontstr);
1015
1016         if (fontsize > 1) {
1017                 FcPatternDel(pattern, FC_PIXEL_SIZE);
1018                 FcPatternDel(pattern, FC_SIZE);
1019                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
1020                 usedfontsize = fontsize;
1021         } else {
1022                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
1023                                 FcResultMatch) {
1024                         usedfontsize = fontval;
1025                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
1026                                 FcResultMatch) {
1027                         usedfontsize = -1;
1028                 } else {
1029                         /*
1030                          * Default font size is 12, if none given. This is to
1031                          * have a known usedfontsize value.
1032                          */
1033                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1034                         usedfontsize = 12;
1035                 }
1036                 defaultfontsize = usedfontsize;
1037         }
1038
1039         if (xloadfont(&dc.font, pattern))
1040                 die("can't open font %s\n", fontstr);
1041
1042         if (usedfontsize < 0) {
1043                 FcPatternGetDouble(dc.font.match->pattern,
1044                                    FC_PIXEL_SIZE, 0, &fontval);
1045                 usedfontsize = fontval;
1046                 if (fontsize == 0)
1047                         defaultfontsize = fontval;
1048         }
1049
1050         /* Setting character width and height. */
1051         win.cw = ceilf(dc.font.width * cwscale);
1052         win.ch = ceilf(dc.font.height * chscale);
1053
1054         FcPatternDel(pattern, FC_SLANT);
1055         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1056         if (xloadfont(&dc.ifont, pattern))
1057                 die("can't open font %s\n", fontstr);
1058
1059         FcPatternDel(pattern, FC_WEIGHT);
1060         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1061         if (xloadfont(&dc.ibfont, pattern))
1062                 die("can't open font %s\n", fontstr);
1063
1064         FcPatternDel(pattern, FC_SLANT);
1065         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1066         if (xloadfont(&dc.bfont, pattern))
1067                 die("can't open font %s\n", fontstr);
1068
1069         FcPatternDestroy(pattern);
1070 }
1071
1072 void
1073 xunloadfont(Font *f)
1074 {
1075         XftFontClose(xw.dpy, f->match);
1076         FcPatternDestroy(f->pattern);
1077         if (f->set)
1078                 FcFontSetDestroy(f->set);
1079 }
1080
1081 void
1082 xunloadfonts(void)
1083 {
1084         /* Free the loaded fonts in the font cache.  */
1085         while (frclen > 0)
1086                 XftFontClose(xw.dpy, frc[--frclen].font);
1087
1088         xunloadfont(&dc.font);
1089         xunloadfont(&dc.bfont);
1090         xunloadfont(&dc.ifont);
1091         xunloadfont(&dc.ibfont);
1092 }
1093
1094 int
1095 ximopen(Display *dpy)
1096 {
1097         XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1098         XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1099
1100         xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1101         if (xw.ime.xim == NULL)
1102                 return 0;
1103
1104         if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1105                 fprintf(stderr, "XSetIMValues: "
1106                                 "Could not set XNDestroyCallback.\n");
1107
1108         xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1109                                               NULL);
1110
1111         if (xw.ime.xic == NULL) {
1112                 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1113                                        XIMPreeditNothing | XIMStatusNothing,
1114                                        XNClientWindow, xw.win,
1115                                        XNDestroyCallback, &icdestroy,
1116                                        NULL);
1117         }
1118         if (xw.ime.xic == NULL)
1119                 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1120
1121         return 1;
1122 }
1123
1124 void
1125 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1126 {
1127         if (ximopen(dpy))
1128                 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1129                                                  ximinstantiate, NULL);
1130 }
1131
1132 void
1133 ximdestroy(XIM xim, XPointer client, XPointer call)
1134 {
1135         xw.ime.xim = NULL;
1136         XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1137                                        ximinstantiate, NULL);
1138         XFree(xw.ime.spotlist);
1139 }
1140
1141 int
1142 xicdestroy(XIC xim, XPointer client, XPointer call)
1143 {
1144         xw.ime.xic = NULL;
1145         return 1;
1146 }
1147
1148 void
1149 xinit(int cols, int rows)
1150 {
1151         XGCValues gcvalues;
1152         Cursor cursor;
1153         Window parent;
1154         pid_t thispid = getpid();
1155         XColor xmousefg, xmousebg;
1156         XWindowAttributes attr;
1157         XVisualInfo vis;
1158
1159         if (!(xw.dpy = XOpenDisplay(NULL)))
1160                 die("can't open display\n");
1161         xw.scr = XDefaultScreen(xw.dpy);
1162
1163         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
1164                 parent = XRootWindow(xw.dpy, xw.scr);
1165                 xw.depth = 32;
1166         } else {
1167                 XGetWindowAttributes(xw.dpy, parent, &attr);
1168                 xw.depth = attr.depth;
1169         }
1170
1171         XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
1172         xw.vis = vis.visual;
1173
1174         /* font */
1175         if (!FcInit())
1176                 die("could not init fontconfig.\n");
1177
1178         usedfont = (opt_font == NULL)? font : opt_font;
1179         xloadfonts(usedfont, 0);
1180
1181         /* colors */
1182         xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
1183         xloadcols();
1184
1185         /* adjust fixed window geometry */
1186         win.w = 2 * borderpx + cols * win.cw;
1187         win.h = 2 * borderpx + rows * win.ch;
1188         if (xw.gm & XNegative)
1189                 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1190         if (xw.gm & YNegative)
1191                 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1192
1193         /* Events */
1194         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1195         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1196         xw.attrs.bit_gravity = NorthWestGravity;
1197         xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1198                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1199                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1200         xw.attrs.colormap = xw.cmap;
1201
1202         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1203                         win.w, win.h, 0, xw.depth, InputOutput,
1204                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1205                         | CWEventMask | CWColormap, &xw.attrs);
1206
1207         memset(&gcvalues, 0, sizeof(gcvalues));
1208         gcvalues.graphics_exposures = False;
1209         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
1210         dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues);
1211         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1212         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1213
1214         /* font spec buffer */
1215         xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1216
1217         /* Xft rendering context */
1218         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1219
1220         /* input methods */
1221         if (!ximopen(xw.dpy)) {
1222                 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1223                                                ximinstantiate, NULL);
1224         }
1225
1226         /* white cursor, black outline */
1227         cursor = XCreateFontCursor(xw.dpy, mouseshape);
1228         XDefineCursor(xw.dpy, xw.win, cursor);
1229
1230         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1231                 xmousefg.red   = 0xffff;
1232                 xmousefg.green = 0xffff;
1233                 xmousefg.blue  = 0xffff;
1234         }
1235
1236         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1237                 xmousebg.red   = 0x0000;
1238                 xmousebg.green = 0x0000;
1239                 xmousebg.blue  = 0x0000;
1240         }
1241
1242         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1243
1244         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1245         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1246         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1247         xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1248         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1249
1250         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1251         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1252                         PropModeReplace, (uchar *)&thispid, 1);
1253
1254         win.mode = MODE_NUMLOCK;
1255         resettitle();
1256         xhints();
1257         XMapWindow(xw.dpy, xw.win);
1258         XSync(xw.dpy, False);
1259
1260         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1261         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1262         xsel.primary = NULL;
1263         xsel.clipboard = NULL;
1264         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1265         if (xsel.xtarget == None)
1266                 xsel.xtarget = XA_STRING;
1267 }
1268
1269 int
1270 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1271 {
1272         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1273         ushort mode, prevmode = USHRT_MAX;
1274         Font *font = &dc.font;
1275         int frcflags = FRC_NORMAL;
1276         float runewidth = win.cw;
1277         Rune rune;
1278         FT_UInt glyphidx;
1279         FcResult fcres;
1280         FcPattern *fcpattern, *fontpattern;
1281         FcFontSet *fcsets[] = { NULL };
1282         FcCharSet *fccharset;
1283         int i, f, numspecs = 0;
1284
1285         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1286                 /* Fetch rune and mode for current glyph. */
1287                 rune = glyphs[i].u;
1288                 mode = glyphs[i].mode;
1289
1290                 /* Skip dummy wide-character spacing. */
1291                 if (mode == ATTR_WDUMMY)
1292                         continue;
1293
1294                 /* Determine font for glyph if different from previous glyph. */
1295                 if (prevmode != mode) {
1296                         prevmode = mode;
1297                         font = &dc.font;
1298                         frcflags = FRC_NORMAL;
1299                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1300                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1301                                 font = &dc.ibfont;
1302                                 frcflags = FRC_ITALICBOLD;
1303                         } else if (mode & ATTR_ITALIC) {
1304                                 font = &dc.ifont;
1305                                 frcflags = FRC_ITALIC;
1306                         } else if (mode & ATTR_BOLD) {
1307                                 font = &dc.bfont;
1308                                 frcflags = FRC_BOLD;
1309                         }
1310                         yp = winy + font->ascent;
1311                 }
1312
1313                 /* Lookup character index with default font. */
1314                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1315                 if (glyphidx) {
1316                         specs[numspecs].font = font->match;
1317                         specs[numspecs].glyph = glyphidx;
1318                         specs[numspecs].x = (short)xp;
1319                         specs[numspecs].y = (short)yp;
1320                         xp += runewidth;
1321                         numspecs++;
1322                         continue;
1323                 }
1324
1325                 /* Fallback on font cache, search the font cache for match. */
1326                 for (f = 0; f < frclen; f++) {
1327                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1328                         /* Everything correct. */
1329                         if (glyphidx && frc[f].flags == frcflags)
1330                                 break;
1331                         /* We got a default font for a not found glyph. */
1332                         if (!glyphidx && frc[f].flags == frcflags
1333                                         && frc[f].unicodep == rune) {
1334                                 break;
1335                         }
1336                 }
1337
1338                 /* Nothing was found. Use fontconfig to find matching font. */
1339                 if (f >= frclen) {
1340                         if (!font->set)
1341                                 font->set = FcFontSort(0, font->pattern,
1342                                                        1, 0, &fcres);
1343                         fcsets[0] = font->set;
1344
1345                         /*
1346                          * Nothing was found in the cache. Now use
1347                          * some dozen of Fontconfig calls to get the
1348                          * font for one single character.
1349                          *
1350                          * Xft and fontconfig are design failures.
1351                          */
1352                         fcpattern = FcPatternDuplicate(font->pattern);
1353                         fccharset = FcCharSetCreate();
1354
1355                         FcCharSetAddChar(fccharset, rune);
1356                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1357                                         fccharset);
1358                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1359
1360                         FcConfigSubstitute(0, fcpattern,
1361                                         FcMatchPattern);
1362                         FcDefaultSubstitute(fcpattern);
1363
1364                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1365                                         fcpattern, &fcres);
1366
1367                         /* Allocate memory for the new cache entry. */
1368                         if (frclen >= frccap) {
1369                                 frccap += 16;
1370                                 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1371                         }
1372
1373                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1374                                         fontpattern);
1375                         if (!frc[frclen].font)
1376                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1377                                         strerror(errno));
1378                         frc[frclen].flags = frcflags;
1379                         frc[frclen].unicodep = rune;
1380
1381                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1382
1383                         f = frclen;
1384                         frclen++;
1385
1386                         FcPatternDestroy(fcpattern);
1387                         FcCharSetDestroy(fccharset);
1388                 }
1389
1390                 specs[numspecs].font = frc[f].font;
1391                 specs[numspecs].glyph = glyphidx;
1392                 specs[numspecs].x = (short)xp;
1393                 specs[numspecs].y = (short)yp;
1394                 xp += runewidth;
1395                 numspecs++;
1396         }
1397
1398         return numspecs;
1399 }
1400
1401 static int isSlopeRising (int x, int iPoint, int waveWidth)
1402 {
1403         //    .     .     .     .
1404         //   / \   / \   / \   / \
1405         //  /   \ /   \ /   \ /   \
1406         // .     .     .     .     .
1407
1408         // Find absolute `x` of point
1409         x += iPoint * (waveWidth/2);
1410
1411         // Find index of absolute wave
1412         int absSlope = x / ((float)waveWidth/2);
1413
1414         return (absSlope % 2);
1415 }
1416
1417 static int getSlope (int x, int iPoint, int waveWidth)
1418 {
1419         // Sizes: Caps are half width of slopes
1420         //    1_2       1_2       1_2      1_2
1421         //   /   \     /   \     /   \    /   \
1422         //  /     \   /     \   /     \  /     \
1423         // 0       3_0       3_0      3_0       3_
1424         // <2->    <1>         <---6---->
1425
1426         // Find type of first point
1427         int firstType;
1428         x -= (x / waveWidth) * waveWidth;
1429         if (x < (waveWidth * (2.f/6.f)))
1430                 firstType = UNDERCURL_SLOPE_ASCENDING;
1431         else if (x < (waveWidth * (3.f/6.f)))
1432                 firstType = UNDERCURL_SLOPE_TOP_CAP;
1433         else if (x < (waveWidth * (5.f/6.f)))
1434                 firstType = UNDERCURL_SLOPE_DESCENDING;
1435         else
1436                 firstType = UNDERCURL_SLOPE_BOTTOM_CAP;
1437
1438         // Find type of given point
1439         int pointType = (iPoint % 4);
1440         pointType += firstType;
1441         pointType %= 4;
1442
1443         return pointType;
1444 }
1445
1446 void
1447 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1448 {
1449         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1450         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1451             width = charlen * win.cw;
1452         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1453         XRenderColor colfg, colbg;
1454         XRectangle r;
1455
1456         /* Fallback on color display for attributes not supported by the font */
1457         if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1458                 if (dc.ibfont.badslant || dc.ibfont.badweight)
1459                         base.fg = defaultattr;
1460         } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1461             (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1462                 base.fg = defaultattr;
1463         }
1464
1465         if (IS_TRUECOL(base.fg)) {
1466                 colfg.alpha = 0xffff;
1467                 colfg.red = TRUERED(base.fg);
1468                 colfg.green = TRUEGREEN(base.fg);
1469                 colfg.blue = TRUEBLUE(base.fg);
1470                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1471                 fg = &truefg;
1472         } else {
1473                 fg = &dc.col[base.fg];
1474         }
1475
1476         if (IS_TRUECOL(base.bg)) {
1477                 colbg.alpha = 0xffff;
1478                 colbg.green = TRUEGREEN(base.bg);
1479                 colbg.red = TRUERED(base.bg);
1480                 colbg.blue = TRUEBLUE(base.bg);
1481                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1482                 bg = &truebg;
1483         } else {
1484                 bg = &dc.col[base.bg];
1485         }
1486
1487         /* Change basic system colors [0-7] to bright system colors [8-15] */
1488         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1489                 fg = &dc.col[base.fg + 8];
1490
1491         if (IS_SET(MODE_REVERSE)) {
1492                 if (fg == &dc.col[defaultfg]) {
1493                         fg = &dc.col[defaultbg];
1494                 } else {
1495                         colfg.red = ~fg->color.red;
1496                         colfg.green = ~fg->color.green;
1497                         colfg.blue = ~fg->color.blue;
1498                         colfg.alpha = fg->color.alpha;
1499                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1500                                         &revfg);
1501                         fg = &revfg;
1502                 }
1503
1504                 if (bg == &dc.col[defaultbg]) {
1505                         bg = &dc.col[defaultfg];
1506                 } else {
1507                         colbg.red = ~bg->color.red;
1508                         colbg.green = ~bg->color.green;
1509                         colbg.blue = ~bg->color.blue;
1510                         colbg.alpha = bg->color.alpha;
1511                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1512                                         &revbg);
1513                         bg = &revbg;
1514                 }
1515         }
1516
1517         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1518                 colfg.red = fg->color.red / 2;
1519                 colfg.green = fg->color.green / 2;
1520                 colfg.blue = fg->color.blue / 2;
1521                 colfg.alpha = fg->color.alpha;
1522                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1523                 fg = &revfg;
1524         }
1525
1526         if (base.mode & ATTR_REVERSE) {
1527                 temp = fg;
1528                 fg = bg;
1529                 bg = temp;
1530         }
1531
1532         if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1533                 fg = bg;
1534
1535         if (base.mode & ATTR_INVISIBLE)
1536                 fg = bg;
1537
1538         /* Intelligent cleaning up of the borders. */
1539         if (x == 0) {
1540                 xclear(0, (y == 0)? 0 : winy, borderpx,
1541                         winy + win.ch +
1542                         ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1543         }
1544         if (winx + width >= borderpx + win.tw) {
1545                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1546                         ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1547         }
1548         if (y == 0)
1549                 xclear(winx, 0, winx + width, borderpx);
1550         if (winy + win.ch >= borderpx + win.th)
1551                 xclear(winx, winy + win.ch, winx + width, win.h);
1552
1553         /* Clean up the region we want to draw to. */
1554         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1555
1556         /* Set the clip region because Xft is sometimes dirty. */
1557         r.x = 0;
1558         r.y = 0;
1559         r.height = win.ch;
1560         r.width = width;
1561         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1562
1563         /* Render the glyphs. */
1564         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1565
1566         /* Render underline and strikethrough. */
1567         if (base.mode & ATTR_UNDERLINE) {
1568                 // Underline Color
1569                 const int widthThreshold  = 28; // +1 width every widthThreshold px of font
1570                 int wlw = (win.ch / widthThreshold) + 1; // Wave Line Width
1571                 int linecolor;
1572                 if ((base.ucolor[0] >= 0) &&
1573                         !(base.mode & ATTR_BLINK && win.mode & MODE_BLINK) &&
1574                         !(base.mode & ATTR_INVISIBLE)
1575                 ) {
1576                         // Special color for underline
1577                         // Index
1578                         if (base.ucolor[1] < 0) {
1579                                 linecolor = dc.col[base.ucolor[0]].pixel;
1580                         }
1581                         // RGB
1582                         else {
1583                                 XColor lcolor;
1584                                 lcolor.red = base.ucolor[0] * 257;
1585                                 lcolor.green = base.ucolor[1] * 257;
1586                                 lcolor.blue = base.ucolor[2] * 257;
1587                                 lcolor.flags = DoRed | DoGreen | DoBlue;
1588                                 XAllocColor(xw.dpy, xw.cmap, &lcolor);
1589                                 linecolor = lcolor.pixel;
1590                         }
1591                 } else {
1592                         // Foreground color for underline
1593                         linecolor = fg->pixel;
1594                 }
1595
1596                 XGCValues ugcv = {
1597                         .foreground = linecolor,
1598                         .line_width = wlw,
1599                         .line_style = LineSolid,
1600                         .cap_style = CapNotLast
1601                 };
1602
1603                 GC ugc = XCreateGC(xw.dpy, XftDrawDrawable(xw.draw),
1604                         GCForeground | GCLineWidth | GCLineStyle | GCCapStyle,
1605                         &ugcv);
1606
1607                 // Underline Style
1608                 if (base.ustyle != 3) {
1609                         //XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, width, 1);
1610                         XFillRectangle(xw.dpy, XftDrawDrawable(xw.draw), ugc, winx,
1611                                 winy + dc.font.ascent + 1, width, wlw);
1612                 } else if (base.ustyle == 3) {
1613                         int ww = win.cw;//width;
1614                         int wh = dc.font.descent - wlw/2 - 1;//r.height/7;
1615                         int wx = winx;
1616                         int wy = winy + win.ch - dc.font.descent;
1617
1618 #if UNDERCURL_STYLE == UNDERCURL_CURLY
1619                         // Draw waves
1620                         int narcs = charlen * 2 + 1;
1621                         XArc *arcs = xmalloc(sizeof(XArc) * narcs);
1622
1623                         int i = 0;
1624                         for (i = 0; i < charlen-1; i++) {
1625                                 arcs[i*2] = (XArc) {
1626                                         .x = wx + win.cw * i + ww / 4,
1627                                         .y = wy,
1628                                         .width = win.cw / 2,
1629                                         .height = wh,
1630                                         .angle1 = 0,
1631                                         .angle2 = 180 * 64
1632                                 };
1633                                 arcs[i*2+1] = (XArc) {
1634                                         .x = wx + win.cw * i + ww * 0.75,
1635                                         .y = wy,
1636                                         .width = win.cw/2,
1637                                         .height = wh,
1638                                         .angle1 = 180 * 64,
1639                                         .angle2 = 180 * 64
1640                                 };
1641                         }
1642                         // Last wave
1643                         arcs[i*2] = (XArc) {wx + ww * i + ww / 4, wy, ww / 2, wh,
1644                         0, 180 * 64 };
1645                         // Last wave tail
1646                         arcs[i*2+1] = (XArc) {wx + ww * i + ww * 0.75, wy, ceil(ww / 2.),
1647                         wh, 180 * 64, 90 * 64};
1648                         // First wave tail
1649                         i++;
1650                         arcs[i*2] = (XArc) {wx - ww/4 - 1, wy, ceil(ww / 2.), wh, 270 * 64,
1651                         90 * 64 };
1652
1653                         XDrawArcs(xw.dpy, XftDrawDrawable(xw.draw), ugc, arcs, narcs);
1654
1655                         free(arcs);
1656 #elif UNDERCURL_STYLE == UNDERCURL_SPIKY
1657                         // Make the underline corridor larger
1658                         /*
1659                         wy -= wh;
1660                         */
1661                         wh *= 2;
1662
1663                         // Set the angle of the slope to 45°
1664                         ww = wh;
1665
1666                         // Position of wave is independent of word, it's absolute
1667                         wx = (wx / (ww/2)) * (ww/2);
1668
1669                         int marginStart = winx - wx;
1670
1671                         // Calculate number of points with floating precision
1672                         float n = width;                                        // Width of word in pixels
1673                         n = (n / ww) * 2;                                       // Number of slopes (/ or \)
1674                         n += 2;                                                         // Add two last points
1675                         int npoints = n;                                        // Convert to int
1676
1677                         // Total length of underline
1678                         float waveLength = 0;
1679
1680                         if (npoints >= 3) {
1681                                 // We add an aditional slot in case we use a bonus point
1682                                 XPoint *points = xmalloc(sizeof(XPoint) * (npoints + 1));
1683
1684                                 // First point (Starts with the word bounds)
1685                                 points[0] = (XPoint) {
1686                                         .x = wx + marginStart,
1687                                         .y = (isSlopeRising(wx, 0, ww))
1688                                                 ? (wy - marginStart + ww/2.f)
1689                                                 : (wy + marginStart)
1690                                 };
1691
1692                                 // Second point (Goes back to the absolute point coordinates)
1693                                 points[1] = (XPoint) {
1694                                         .x = (ww/2.f) - marginStart,
1695                                         .y = (isSlopeRising(wx, 1, ww))
1696                                                 ? (ww/2.f - marginStart)
1697                                                 : (-ww/2.f + marginStart)
1698                                 };
1699                                 waveLength += (ww/2.f) - marginStart;
1700
1701                                 // The rest of the points
1702                                 for (int i = 2; i < npoints-1; i++) {
1703                                         points[i] = (XPoint) {
1704                                                 .x = ww/2,
1705                                                 .y = (isSlopeRising(wx, i, ww))
1706                                                         ? wh/2
1707                                                         : -wh/2
1708                                         };
1709                                         waveLength += ww/2;
1710                                 }
1711
1712                                 // Last point
1713                                 points[npoints-1] = (XPoint) {
1714                                         .x = ww/2,
1715                                         .y = (isSlopeRising(wx, npoints-1, ww))
1716                                                 ? wh/2
1717                                                 : -wh/2
1718                                 };
1719                                 waveLength += ww/2;
1720
1721                                 // End
1722                                 if (waveLength < width) { // Add a bonus point?
1723                                         int marginEnd = width - waveLength;
1724                                         points[npoints] = (XPoint) {
1725                                                 .x = marginEnd,
1726                                                 .y = (isSlopeRising(wx, npoints, ww))
1727                                                         ? (marginEnd)
1728                                                         : (-marginEnd)
1729                                         };
1730
1731                                         npoints++;
1732                                 } else if (waveLength > width) { // Is last point too far?
1733                                         int marginEnd = waveLength - width;
1734                                         points[npoints-1].x -= marginEnd;
1735                                         if (isSlopeRising(wx, npoints-1, ww))
1736                                                 points[npoints-1].y -= (marginEnd);
1737                                         else
1738                                                 points[npoints-1].y += (marginEnd);
1739                                 }
1740
1741                                 // Draw the lines
1742                                 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points, npoints,
1743                                                 CoordModePrevious);
1744
1745                                 // Draw a second underline with an offset of 1 pixel
1746                                 if ( ((win.ch / (widthThreshold/2)) % 2)) {
1747                                         points[0].x++;
1748
1749                                         XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points,
1750                                                         npoints, CoordModePrevious);
1751                                 }
1752
1753                                 // Free resources
1754                                 free(points);
1755                         }
1756 #else // UNDERCURL_CAPPED
1757                         // Cap is half of wave width
1758                         float capRatio = 0.5f;
1759
1760                         // Make the underline corridor larger
1761                         wh *= 2;
1762
1763                         // Set the angle of the slope to 45°
1764                         ww = wh;
1765                         ww *= 1 + capRatio; // Add a bit of width for the cap
1766
1767                         // Position of wave is independent of word, it's absolute
1768                         wx = (wx / ww) * ww;
1769
1770                         float marginStart;
1771                         switch(getSlope(winx, 0, ww)) {
1772                                 case UNDERCURL_SLOPE_ASCENDING:
1773                                         marginStart = winx - wx;
1774                                         break;
1775                                 case UNDERCURL_SLOPE_TOP_CAP:
1776                                         marginStart = winx - (wx + (ww * (2.f/6.f)));
1777                                         break;
1778                                 case UNDERCURL_SLOPE_DESCENDING:
1779                                         marginStart = winx - (wx + (ww * (3.f/6.f)));
1780                                         break;
1781                                 case UNDERCURL_SLOPE_BOTTOM_CAP:
1782                                         marginStart = winx - (wx + (ww * (5.f/6.f)));
1783                                         break;
1784                         }
1785
1786                         // Calculate number of points with floating precision
1787                         float n = width;                                        // Width of word in pixels
1788                                                                                                 //                                         ._.
1789                         n = (n / ww) * 4;                                       // Number of points (./   \.)
1790                         n += 2;                                                         // Add two last points
1791                         int npoints = n;                                        // Convert to int
1792
1793                         // Position of the pen to draw the lines
1794                         float penX = 0;
1795                         float penY = 0;
1796
1797                         if (npoints >= 3) {
1798                                 XPoint *points = xmalloc(sizeof(XPoint) * (npoints + 1));
1799
1800                                 // First point (Starts with the word bounds)
1801                                 penX = winx;
1802                                 switch (getSlope(winx, 0, ww)) {
1803                                         case UNDERCURL_SLOPE_ASCENDING:
1804                                                 penY = wy + wh/2.f - marginStart;
1805                                                 break;
1806                                         case UNDERCURL_SLOPE_TOP_CAP:
1807                                                 penY = wy;
1808                                                 break;
1809                                         case UNDERCURL_SLOPE_DESCENDING:
1810                                                 penY = wy + marginStart;
1811                                                 break;
1812                                         case UNDERCURL_SLOPE_BOTTOM_CAP:
1813                                                 penY = wy + wh/2.f;
1814                                                 break;
1815                                 }
1816                                 points[0].x = penX;
1817                                 points[0].y = penY;
1818
1819                                 // Second point (Goes back to the absolute point coordinates)
1820                                 switch (getSlope(winx, 1, ww)) {
1821                                         case UNDERCURL_SLOPE_ASCENDING:
1822                                                 penX += ww * (1.f/6.f) - marginStart;
1823                                                 penY += 0;
1824                                                 break;
1825                                         case UNDERCURL_SLOPE_TOP_CAP:
1826                                                 penX += ww * (2.f/6.f) - marginStart;
1827                                                 penY += -wh/2.f + marginStart;
1828                                                 break;
1829                                         case UNDERCURL_SLOPE_DESCENDING:
1830                                                 penX += ww * (1.f/6.f) - marginStart;
1831                                                 penY += 0;
1832                                                 break;
1833                                         case UNDERCURL_SLOPE_BOTTOM_CAP:
1834                                                 penX += ww * (2.f/6.f) - marginStart;
1835                                                 penY += -marginStart + wh/2.f;
1836                                                 break;
1837                                 }
1838                                 points[1].x = penX;
1839                                 points[1].y = penY;
1840
1841                                 // The rest of the points
1842                                 for (int i = 2; i < npoints; i++) {
1843                                         switch (getSlope(winx, i, ww)) {
1844                                                 case UNDERCURL_SLOPE_ASCENDING:
1845                                                 case UNDERCURL_SLOPE_DESCENDING:
1846                                                         penX += ww * (1.f/6.f);
1847                                                         penY += 0;
1848                                                         break;
1849                                                 case UNDERCURL_SLOPE_TOP_CAP:
1850                                                         penX += ww * (2.f/6.f);
1851                                                         penY += -wh / 2.f;
1852                                                         break;
1853                                                 case UNDERCURL_SLOPE_BOTTOM_CAP:
1854                                                         penX += ww * (2.f/6.f);
1855                                                         penY += wh / 2.f;
1856                                                         break;
1857                                         }
1858                                         points[i].x = penX;
1859                                         points[i].y = penY;
1860                                 }
1861
1862                                 // End
1863                                 float waveLength = penX - winx;
1864                                 if (waveLength < width) { // Add a bonus point?
1865                                         int marginEnd = width - waveLength;
1866                                         penX += marginEnd;
1867                                         switch(getSlope(winx, npoints, ww)) {
1868                                                 case UNDERCURL_SLOPE_ASCENDING:
1869                                                 case UNDERCURL_SLOPE_DESCENDING:
1870                                                         //penY += 0;
1871                                                         break;
1872                                                 case UNDERCURL_SLOPE_TOP_CAP:
1873                                                         penY += -marginEnd;
1874                                                         break;
1875                                                 case UNDERCURL_SLOPE_BOTTOM_CAP:
1876                                                         penY += marginEnd;
1877                                                         break;
1878                                         }
1879
1880                                         points[npoints].x = penX;
1881                                         points[npoints].y = penY;
1882
1883                                         npoints++;
1884                                 } else if (waveLength > width) { // Is last point too far?
1885                                         int marginEnd = waveLength - width;
1886                                         points[npoints-1].x -= marginEnd;
1887                                         switch(getSlope(winx, npoints-1, ww)) {
1888                                                 case UNDERCURL_SLOPE_TOP_CAP:
1889                                                         points[npoints-1].y += marginEnd;
1890                                                         break;
1891                                                 case UNDERCURL_SLOPE_BOTTOM_CAP:
1892                                                         points[npoints-1].y -= marginEnd;
1893                                                         break;
1894                                                 default:
1895                                                         break;
1896                                         }
1897                                 }
1898
1899                                 // Draw the lines
1900                                 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points, npoints,
1901                                                 CoordModeOrigin);
1902
1903                                 // Draw a second underline with an offset of 1 pixel
1904                                 if ( ((win.ch / (widthThreshold/2)) % 2)) {
1905                                         for (int i = 0; i < npoints; i++)
1906                                                 points[i].x++;
1907
1908                                         XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points,
1909                                                         npoints, CoordModeOrigin);
1910                                 }
1911
1912                                 // Free resources
1913                                 free(points);
1914                         }
1915 #endif
1916                 }
1917
1918                 XFreeGC(xw.dpy, ugc);
1919         }
1920
1921         if (base.mode & ATTR_STRUCK) {
1922                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1923                                 width, 1);
1924         }
1925
1926         /* Reset clip to none. */
1927         XftDrawSetClip(xw.draw, 0);
1928 }
1929
1930 void
1931 xdrawglyph(Glyph g, int x, int y)
1932 {
1933         int numspecs;
1934         XftGlyphFontSpec spec;
1935
1936         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1937         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1938 }
1939
1940 void
1941 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1942 {
1943         Color drawcol;
1944         XRenderColor colbg;
1945
1946         /* remove the old cursor */
1947         if (selected(ox, oy))
1948                 og.mode ^= ATTR_REVERSE;
1949         xdrawglyph(og, ox, oy);
1950
1951         if (IS_SET(MODE_HIDE))
1952                 return;
1953
1954         /*
1955          * Select the right color for the right mode.
1956          */
1957         g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1958
1959         if (IS_SET(MODE_REVERSE)) {
1960                 g.mode |= ATTR_REVERSE;
1961                 g.bg = defaultfg;
1962                 if (selected(cx, cy)) {
1963                         drawcol = dc.col[defaultcs];
1964                         g.fg = defaultrcs;
1965                 } else {
1966                         drawcol = dc.col[defaultrcs];
1967                         g.fg = defaultcs;
1968                 }
1969         } else {
1970                 if (selected(cx, cy)) {
1971                         g.fg = defaultfg;
1972                         g.bg = defaultrcs;
1973                 } else {
1974                         /** this is the main part of the dynamic cursor color patch */
1975                         g.bg = g.fg;
1976                         g.fg = defaultbg;
1977                 }
1978
1979                 /**
1980                  * and this is the second part of the dynamic cursor color patch.
1981                  * it handles the `drawcol` variable
1982                 */
1983                 if (IS_TRUECOL(g.bg)) {
1984                         colbg.alpha = 0xffff;
1985                         colbg.red = TRUERED(g.bg);
1986                         colbg.green = TRUEGREEN(g.bg);
1987                         colbg.blue = TRUEBLUE(g.bg);
1988                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &drawcol);
1989                 } else {
1990                         drawcol = dc.col[g.bg];
1991                 }
1992         }
1993
1994         /* draw the new one */
1995         if (IS_SET(MODE_FOCUSED)) {
1996                 switch (win.cursor) {
1997                 case 7: /* st extension */
1998                         g.u = 0x2603; /* snowman (U+2603) */
1999                         /* FALLTHROUGH */
2000                 case 0: /* Blinking Block */
2001                 case 1: /* Blinking Block (Default) */
2002                 case 2: /* Steady Block */
2003                         xdrawglyph(g, cx, cy);
2004                         break;
2005                 case 3: /* Blinking Underline */
2006                 case 4: /* Steady Underline */
2007                         XftDrawRect(xw.draw, &drawcol,
2008                                         borderpx + cx * win.cw,
2009                                         borderpx + (cy + 1) * win.ch - \
2010                                                 cursorthickness,
2011                                         win.cw, cursorthickness);
2012                         break;
2013                 case 5: /* Blinking bar */
2014                 case 6: /* Steady bar */
2015                         XftDrawRect(xw.draw, &drawcol,
2016                                         borderpx + cx * win.cw,
2017                                         borderpx + cy * win.ch,
2018                                         cursorthickness, win.ch);
2019                         break;
2020                 }
2021         } else {
2022                 XftDrawRect(xw.draw, &drawcol,
2023                                 borderpx + cx * win.cw,
2024                                 borderpx + cy * win.ch,
2025                                 win.cw - 1, 1);
2026                 XftDrawRect(xw.draw, &drawcol,
2027                                 borderpx + cx * win.cw,
2028                                 borderpx + cy * win.ch,
2029                                 1, win.ch - 1);
2030                 XftDrawRect(xw.draw, &drawcol,
2031                                 borderpx + (cx + 1) * win.cw - 1,
2032                                 borderpx + cy * win.ch,
2033                                 1, win.ch - 1);
2034                 XftDrawRect(xw.draw, &drawcol,
2035                                 borderpx + cx * win.cw,
2036                                 borderpx + (cy + 1) * win.ch - 1,
2037                                 win.cw, 1);
2038         }
2039 }
2040
2041 void
2042 xsetenv(void)
2043 {
2044         char buf[sizeof(long) * 8 + 1];
2045
2046         snprintf(buf, sizeof(buf), "%lu", xw.win);
2047         setenv("WINDOWID", buf, 1);
2048 }
2049
2050 void
2051 xseticontitle(char *p)
2052 {
2053         XTextProperty prop;
2054         DEFAULT(p, opt_title);
2055
2056         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2057                                         &prop) != Success)
2058                 return;
2059         XSetWMIconName(xw.dpy, xw.win, &prop);
2060         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
2061         XFree(prop.value);
2062 }
2063
2064 void
2065 xsettitle(char *p)
2066 {
2067         XTextProperty prop;
2068         DEFAULT(p, opt_title);
2069
2070         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2071                                         &prop) != Success)
2072                 return;
2073         XSetWMName(xw.dpy, xw.win, &prop);
2074         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
2075         XFree(prop.value);
2076 }
2077
2078 int
2079 xstartdraw(void)
2080 {
2081         if (IS_SET(MODE_VISIBLE))
2082                 XCopyArea(xw.dpy, xw.win, xw.buf, dc.gc, 0, 0, win.w, win.h, 0, 0);
2083         return IS_SET(MODE_VISIBLE);
2084 }
2085
2086 void
2087 xdrawline(Line line, int x1, int y1, int x2)
2088 {
2089         int i, x, ox, numspecs;
2090         Glyph base, new;
2091         XftGlyphFontSpec *specs = xw.specbuf;
2092
2093         numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
2094         i = ox = 0;
2095         for (x = x1; x < x2 && i < numspecs; x++) {
2096                 new = line[x];
2097                 if (new.mode == ATTR_WDUMMY)
2098                         continue;
2099                 if (selected(x, y1))
2100                         new.mode ^= ATTR_REVERSE;
2101                 if (i > 0 && ATTRCMP(base, new)) {
2102                         xdrawglyphfontspecs(specs, base, i, ox, y1);
2103                         specs += i;
2104                         numspecs -= i;
2105                         i = 0;
2106                 }
2107                 if (i == 0) {
2108                         ox = x;
2109                         base = new;
2110                 }
2111                 i++;
2112         }
2113         if (i > 0)
2114                 xdrawglyphfontspecs(specs, base, i, ox, y1);
2115 }
2116
2117 void
2118 xfinishdraw(void)
2119 {
2120         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
2121                         win.h, 0, 0);
2122         XSetForeground(xw.dpy, dc.gc,
2123                         dc.col[IS_SET(MODE_REVERSE)?
2124                                 defaultfg : defaultbg].pixel);
2125 }
2126
2127 void
2128 xximspot(int x, int y)
2129 {
2130         if (xw.ime.xic == NULL)
2131                 return;
2132
2133         xw.ime.spot.x = borderpx + x * win.cw;
2134         xw.ime.spot.y = borderpx + (y + 1) * win.ch;
2135
2136         XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
2137 }
2138
2139 void
2140 expose(XEvent *ev)
2141 {
2142         redraw();
2143 }
2144
2145 void
2146 visibility(XEvent *ev)
2147 {
2148         XVisibilityEvent *e = &ev->xvisibility;
2149
2150         MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
2151 }
2152
2153 void
2154 unmap(XEvent *ev)
2155 {
2156         win.mode &= ~MODE_VISIBLE;
2157 }
2158
2159 void
2160 xsetpointermotion(int set)
2161 {
2162         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
2163         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
2164 }
2165
2166 void
2167 xsetmode(int set, unsigned int flags)
2168 {
2169         int mode = win.mode;
2170         MODBIT(win.mode, set, flags);
2171         if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
2172                 redraw();
2173 }
2174
2175 int
2176 xsetcursor(int cursor)
2177 {
2178         if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
2179                 return 1;
2180         win.cursor = cursor;
2181         return 0;
2182 }
2183
2184 void
2185 xseturgency(int add)
2186 {
2187         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2188
2189         MODBIT(h->flags, add, XUrgencyHint);
2190         XSetWMHints(xw.dpy, xw.win, h);
2191         XFree(h);
2192 }
2193
2194 void
2195 xbell(void)
2196 {
2197         if (!(IS_SET(MODE_FOCUSED)))
2198                 xseturgency(1);
2199         if (bellvolume)
2200                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2201 }
2202
2203 void
2204 focus(XEvent *ev)
2205 {
2206         XFocusChangeEvent *e = &ev->xfocus;
2207
2208         if (e->mode == NotifyGrab)
2209                 return;
2210
2211         if (ev->type == FocusIn) {
2212                 if (xw.ime.xic)
2213                         XSetICFocus(xw.ime.xic);
2214                 win.mode |= MODE_FOCUSED;
2215                 xseturgency(0);
2216                 if (IS_SET(MODE_FOCUS))
2217                         ttywrite("\033[I", 3, 0);
2218         } else {
2219                 if (xw.ime.xic)
2220                         XUnsetICFocus(xw.ime.xic);
2221                 win.mode &= ~MODE_FOCUSED;
2222                 if (IS_SET(MODE_FOCUS))
2223                         ttywrite("\033[O", 3, 0);
2224         }
2225 }
2226
2227 int
2228 match(uint mask, uint state)
2229 {
2230         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
2231 }
2232
2233 char*
2234 kmap(KeySym k, uint state)
2235 {
2236         Key *kp;
2237         int i;
2238
2239         /* Check for mapped keys out of X11 function keys. */
2240         for (i = 0; i < LEN(mappedkeys); i++) {
2241                 if (mappedkeys[i] == k)
2242                         break;
2243         }
2244         if (i == LEN(mappedkeys)) {
2245                 if ((k & 0xFFFF) < 0xFD00)
2246                         return NULL;
2247         }
2248
2249         for (kp = key; kp < key + LEN(key); kp++) {
2250                 if (kp->k != k)
2251                         continue;
2252
2253                 if (!match(kp->mask, state))
2254                         continue;
2255
2256                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
2257                         continue;
2258                 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
2259                         continue;
2260
2261                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
2262                         continue;
2263
2264                 return kp->s;
2265         }
2266
2267         return NULL;
2268 }
2269
2270 void
2271 kpress(XEvent *ev)
2272 {
2273         XKeyEvent *e = &ev->xkey;
2274         KeySym ksym;
2275         char buf[64], *customkey;
2276         int len;
2277         Rune c;
2278         Status status;
2279         Shortcut *bp;
2280
2281         if (IS_SET(MODE_KBDLOCK))
2282                 return;
2283
2284         if (xw.ime.xic)
2285                 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
2286         else
2287                 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
2288         /* 1. shortcuts */
2289         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
2290                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
2291                         bp->func(&(bp->arg));
2292                         return;
2293                 }
2294         }
2295
2296         /* 2. custom keys from config.h */
2297         if ((customkey = kmap(ksym, e->state))) {
2298                 ttywrite(customkey, strlen(customkey), 1);
2299                 return;
2300         }
2301
2302         /* 3. composed string from input method */
2303         if (len == 0)
2304                 return;
2305         if (len == 1 && e->state & Mod1Mask) {
2306                 if (IS_SET(MODE_8BIT)) {
2307                         if (*buf < 0177) {
2308                                 c = *buf | 0x80;
2309                                 len = utf8encode(c, buf);
2310                         }
2311                 } else {
2312                         buf[1] = buf[0];
2313                         buf[0] = '\033';
2314                         len = 2;
2315                 }
2316         }
2317         ttywrite(buf, len, 1);
2318 }
2319
2320 void
2321 cmessage(XEvent *e)
2322 {
2323         /*
2324          * See xembed specs
2325          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
2326          */
2327         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2328                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2329                         win.mode |= MODE_FOCUSED;
2330                         xseturgency(0);
2331                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2332                         win.mode &= ~MODE_FOCUSED;
2333                 }
2334         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
2335                 ttyhangup();
2336                 exit(0);
2337         }
2338 }
2339
2340 void
2341 resize(XEvent *e)
2342 {
2343         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
2344                 return;
2345
2346         cresize(e->xconfigure.width, e->xconfigure.height);
2347 }
2348
2349 int tinsync(uint);
2350 int ttyread_pending();
2351
2352 void
2353 run(void)
2354 {
2355         XEvent ev;
2356         int w = win.w, h = win.h;
2357         fd_set rfd;
2358         int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
2359         struct timespec seltv, *tv, now, lastblink, trigger;
2360         double timeout;
2361
2362         /* Waiting for window mapping */
2363         do {
2364                 XNextEvent(xw.dpy, &ev);
2365                 /*
2366                  * This XFilterEvent call is required because of XOpenIM. It
2367                  * does filter out the key event and some client message for
2368                  * the input method too.
2369                  */
2370                 if (XFilterEvent(&ev, None))
2371                         continue;
2372                 if (ev.type == ConfigureNotify) {
2373                         w = ev.xconfigure.width;
2374                         h = ev.xconfigure.height;
2375                 }
2376         } while (ev.type != MapNotify);
2377
2378         ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
2379         cresize(w, h);
2380
2381         for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
2382                 FD_ZERO(&rfd);
2383                 FD_SET(ttyfd, &rfd);
2384                 FD_SET(xfd, &rfd);
2385
2386                 if (XPending(xw.dpy) || ttyread_pending())
2387                         timeout = 0;  /* existing events might not set xfd */
2388
2389                 seltv.tv_sec = timeout / 1E3;
2390                 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
2391                 tv = timeout >= 0 ? &seltv : NULL;
2392
2393                 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
2394                         if (errno == EINTR)
2395                                 continue;
2396                         die("select failed: %s\n", strerror(errno));
2397                 }
2398                 clock_gettime(CLOCK_MONOTONIC, &now);
2399
2400                 int ttyin = FD_ISSET(ttyfd, &rfd) || ttyread_pending();
2401                 if (ttyin)
2402                         ttyread();
2403
2404                 xev = 0;
2405                 while (XPending(xw.dpy)) {
2406                         xev = 1;
2407                         XNextEvent(xw.dpy, &ev);
2408                         if (XFilterEvent(&ev, None))
2409                                 continue;
2410                         if (handler[ev.type])
2411                                 (handler[ev.type])(&ev);
2412                 }
2413
2414                 /*
2415                  * To reduce flicker and tearing, when new content or event
2416                  * triggers drawing, we first wait a bit to ensure we got
2417                  * everything, and if nothing new arrives - we draw.
2418                  * We start with trying to wait minlatency ms. If more content
2419                  * arrives sooner, we retry with shorter and shorter periods,
2420                  * and eventually draw even without idle after maxlatency ms.
2421                  * Typically this results in low latency while interacting,
2422                  * maximum latency intervals during `cat huge.txt`, and perfect
2423                  * sync with periodic updates from animations/key-repeats/etc.
2424                  */
2425                 if (ttyin || xev) {
2426                         if (!drawing) {
2427                                 trigger = now;
2428                                 drawing = 1;
2429                         }
2430                         timeout = (maxlatency - TIMEDIFF(now, trigger)) \
2431                                   / maxlatency * minlatency;
2432                         if (timeout > 0)
2433                                 continue;  /* we have time, try to find idle */
2434                 }
2435
2436                 if (tinsync(su_timeout)) {
2437                         /*
2438                          * on synchronized-update draw-suspension: don't reset
2439                          * drawing so that we draw ASAP once we can (just after
2440                          * ESU). it won't be too soon because we already can
2441                          * draw now but we skip. we set timeout > 0 to draw on
2442                          * SU-timeout even without new content.
2443                          */
2444                         timeout = minlatency;
2445                         continue;
2446                 }
2447
2448                 /* idle detected or maxlatency exhausted -> draw */
2449                 timeout = -1;
2450                 if (blinktimeout && tattrset(ATTR_BLINK)) {
2451                         timeout = blinktimeout - TIMEDIFF(now, lastblink);
2452                         if (timeout <= 0) {
2453                                 if (-timeout > blinktimeout) /* start visible */
2454                                         win.mode |= MODE_BLINK;
2455                                 win.mode ^= MODE_BLINK;
2456                                 tsetdirtattr(ATTR_BLINK);
2457                                 lastblink = now;
2458                                 timeout = blinktimeout;
2459                         }
2460                 }
2461
2462                 draw();
2463                 XFlush(xw.dpy);
2464                 drawing = 0;
2465         }
2466 }
2467
2468 void
2469 usage(void)
2470 {
2471         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2472             " [-n name] [-o file]\n"
2473             "          [-T title] [-t title] [-w windowid]"
2474             " [[-e] command [args ...]]\n"
2475             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
2476             " [-n name] [-o file]\n"
2477             "          [-T title] [-t title] [-w windowid] -l line"
2478             " [stty_args ...]\n", argv0, argv0);
2479 }
2480
2481 int
2482 main(int argc, char *argv[])
2483 {
2484         xw.l = xw.t = 0;
2485         xw.isfixed = False;
2486         xsetcursor(cursorshape);
2487
2488         ARGBEGIN {
2489         case 'a':
2490                 allowaltscreen = 0;
2491                 break;
2492         case 'A':
2493                 opt_alpha = EARGF(usage());
2494                 break;
2495         case 'c':
2496                 opt_class = EARGF(usage());
2497                 break;
2498         case 'e':
2499                 if (argc > 0)
2500                         --argc, ++argv;
2501                 goto run;
2502         case 'f':
2503                 opt_font = EARGF(usage());
2504                 break;
2505         case 'g':
2506                 xw.gm = XParseGeometry(EARGF(usage()),
2507                                 &xw.l, &xw.t, &cols, &rows);
2508                 break;
2509         case 'i':
2510                 xw.isfixed = 1;
2511                 break;
2512         case 'o':
2513                 opt_io = EARGF(usage());
2514                 break;
2515         case 'l':
2516                 opt_line = EARGF(usage());
2517                 break;
2518         case 'n':
2519                 opt_name = EARGF(usage());
2520                 break;
2521         case 't':
2522         case 'T':
2523                 opt_title = EARGF(usage());
2524                 break;
2525         case 'w':
2526                 opt_embed = EARGF(usage());
2527                 break;
2528         case 'v':
2529                 die("%s " VERSION "\n", argv0);
2530                 break;
2531         default:
2532                 usage();
2533         } ARGEND;
2534
2535 run:
2536         if (argc > 0) /* eat all remaining arguments */
2537                 opt_cmd = argv;
2538
2539         if (!opt_title)
2540                 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2541
2542         setlocale(LC_CTYPE, "");
2543         XSetLocaleModifiers("");
2544         cols = MAX(cols, 1);
2545         rows = MAX(rows, 1);
2546         tnew(cols, rows);
2547         xinit(cols, rows);
2548         xsetenv();
2549         selinit();
2550         run();
2551
2552         return 0;
2553 }