1 /* See LICENSE for license details. */
7 #include <sys/select.h>
11 #include <X11/Xatom.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
23 /* types used in config.h */
27 void (*func)(const Arg *);
34 void (*func)(const Arg *);
37 int altscrn; /* 0: don't care, -1: not alt screen, 1: alt screen */
44 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
45 signed char appkey; /* application keypad */
46 signed char appcursor; /* application cursor */
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
58 #define XK_ANY_MOD UINT_MAX
60 #define XK_SWITCH_MOD (1<<13|1<<14)
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 *);
72 /* config.h for applying patches and the configuration. */
76 #define XEMBED_FOCUS_IN 4
77 #define XEMBED_FOCUS_OUT 5
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)
85 typedef XftDraw *Draw;
86 typedef XftColor Color;
87 typedef XftGlyphFontSpec GlyphFontSpec;
89 /* Purely graphic info */
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 */
104 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
105 Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
110 XVaNestedList spotlist;
114 XSetWindowAttributes attrs;
116 int isfixed; /* is fixed geometry? */
117 int depth; /* bit depth */
118 int l, t; /* left and top offset */
119 int gm; /* geometry mask */
124 char *primary, *clipboard;
125 struct timespec tclick1;
126 struct timespec tclick2;
145 /* Drawing Context */
149 Font font, bfont, ifont, ibfont;
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 *);
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);
199 static void run(void);
200 static void usage(void);
202 static void (*handler[LASTEvent])(XEvent *) = {
204 [ClientMessage] = cmessage,
205 [ConfigureNotify] = resize,
206 [VisibilityNotify] = visibility,
207 [UnmapNotify] = unmap,
211 [MotionNotify] = bmotion,
212 [ButtonPress] = bpress,
213 [ButtonRelease] = brelease,
215 * Uncomment if you want the selection to disappear when you select something
216 * different in another window.
218 /* [SelectionClear] = selclear_, */
219 [SelectionNotify] = selnotify,
221 * PropertyNotify is only turned on when there is some INCR transfer happening
222 * for the selection retrieval.
224 [PropertyNotify] = propnotify,
225 [SelectionRequest] = selrequest,
231 static XSelection xsel;
232 static TermWindow win;
234 /* Font Ring Cache */
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;
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;
266 static uint buttons; /* bit field of pressed buttons */
269 clipcopy(const Arg *dummy)
273 free(xsel.clipboard);
274 xsel.clipboard = NULL;
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);
284 clippaste(const Arg *dummy)
288 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
289 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
290 xw.win, CurrentTime);
294 selpaste(const Arg *dummy)
296 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
297 xw.win, CurrentTime);
301 numlock(const Arg *dummy)
303 win.mode ^= MODE_NUMLOCK;
311 larg.f = usedfontsize + arg->f;
316 zoomabs(const Arg *arg)
319 xloadfonts(usedfont, arg->f);
326 zoomreset(const Arg *arg)
330 if (defaultfontsize > 0) {
331 larg.f = defaultfontsize;
337 ttysend(const Arg *arg)
339 ttywrite(arg->s, strlen(arg->s), 1);
345 int x = e->xbutton.x - borderpx;
346 LIMIT(x, 0, win.tw - 1);
353 int y = e->xbutton.y - borderpx;
354 LIMIT(y, 0, win.th - 1);
359 mousesel(XEvent *e, int done)
361 int type, seltype = SEL_REGULAR;
362 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
364 for (type = 1; type < LEN(selmasks); ++type) {
365 if (match(selmasks[type], state)) {
370 selextend(evcol(e), evrow(e), seltype, done);
372 setsel(getsel(), e->xbutton.time);
376 mousereport(XEvent *e)
379 int x = evcol(e), y = evrow(e);
380 int state = e->xbutton.state;
384 if (e->type == MotionNotify) {
385 if (x == ox && y == oy)
387 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
389 /* MODE_MOUSEMOTION: no reporting if no button is pressed */
390 if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
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++)
398 btn = e->xbutton.button;
399 /* Only buttons 1 through 11 can be encoded */
400 if (btn < 1 || btn > 11)
402 if (e->type == ButtonRelease) {
403 /* MODE_MOUSEX10: no button release reporting */
404 if (IS_SET(MODE_MOUSEX10))
406 /* Don't send release events for the scroll wheel */
407 if (btn == 4 || btn == 5)
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)
421 code += 128 + btn - 8;
423 code += 64 + btn - 4;
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);
433 if (IS_SET(MODE_MOUSESGR)) {
434 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
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);
444 ttywrite(buf, len, 0);
448 buttonmask(uint button)
450 return button == Button1 ? Button1Mask
451 : button == Button2 ? Button2Mask
452 : button == Button3 ? Button3Mask
453 : button == Button4 ? Button4Mask
454 : button == Button5 ? Button5Mask
459 mouseaction(XEvent *e, uint release)
463 /* ignore Button<N>mask for Button<N> - it's set on release */
464 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
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));
483 int btn = e->xbutton.button;
487 if (1 <= btn && btn <= 11)
488 buttons |= 1 << (btn-1);
490 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
495 if (mouseaction(e, 0))
498 if (btn == Button1) {
500 * If the user clicks below predefined timeouts specific
501 * snapping behaviour is exposed.
503 clock_gettime(CLOCK_MONOTONIC, &now);
504 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
506 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
511 xsel.tclick2 = xsel.tclick1;
514 selstart(evcol(e), evrow(e), snap);
519 propnotify(XEvent *e)
521 XPropertyEvent *xpev;
522 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
524 xpev = &e->xproperty;
525 if (xpev->state == PropertyNewValue &&
526 (xpev->atom == XA_PRIMARY ||
527 xpev->atom == clipboard)) {
535 ulong nitems, ofs, rem;
537 uchar *data, *last, *repl;
538 Atom type, incratom, property = None;
540 incratom = XInternAtom(xw.dpy, "INCR", 0);
543 if (e->type == SelectionNotify)
544 property = e->xselection.property;
545 else if (e->type == PropertyNotify)
546 property = e->xproperty.atom;
548 if (property == None)
552 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
553 BUFSIZ/4, False, AnyPropertyType,
554 &type, &format, &nitems, &rem,
556 fprintf(stderr, "Clipboard allocation failed\n");
560 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
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.
567 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
568 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
572 if (type == incratom) {
574 * Activate the PropertyNotify events so we receive
575 * when the selection owner does send us the next
578 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
579 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
583 * Deleting the property is the transfer start signal.
585 XDeleteProperty(xw.dpy, xw.win, (int)property);
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.
597 last = data + nitems * format / 8;
598 while ((repl = memchr(repl, '\n', last - repl))) {
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);
608 /* number of 32-bit chunks returned */
609 ofs += nitems * format / 32;
613 * Deleting the property again tells the selection owner to send the
614 * next data chunk in the property.
616 XDeleteProperty(xw.dpy, xw.win, (int)property);
632 selrequest(XEvent *e)
634 XSelectionRequestEvent *xsre;
636 Atom xa_targets, string, clipboard;
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;
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) {
661 * xith XA_STRING non ascii characters may be incorrect in the
662 * requestor. It is not our problem, use utf8.
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;
671 "Unhandled clipboard selection 0x%lx\n",
675 if (seltext != NULL) {
676 XChangeProperty(xsre->display, xsre->requestor,
677 xsre->property, xsre->target,
679 (uchar *)seltext, strlen(seltext));
680 xev.property = xsre->property;
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");
690 setsel(char *str, Time t)
698 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
699 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
706 setsel(str, CurrentTime);
712 int btn = e->xbutton.button;
714 if (1 <= btn && btn <= 11)
715 buttons &= ~(1 << (btn-1));
717 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
722 if (mouseaction(e, 1))
731 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
740 cresize(int width, int height)
749 col = (win.w - 2 * borderpx) / win.cw;
750 row = (win.h - 2 * borderpx) / win.ch;
756 ttyresize(win.tw, win.th);
760 xresize(int col, int row)
762 win.tw = col * win.cw;
763 win.th = row * win.ch;
765 XFreePixmap(xw.dpy, xw.buf);
766 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
768 XftDrawChange(xw.draw, xw.buf);
769 xclear(0, 0, win.w, win.h);
771 /* resize to new width */
772 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
778 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
782 xloadcolor(int i, const char *name, Color *ncolor)
784 XRenderColor color = { .alpha = 0xffff };
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;
796 return XftColorAllocValue(xw.dpy, xw.vis,
797 xw.cmap, &color, ncolor);
802 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
813 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
814 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
816 dc.collen = MAX(LEN(colorname), 256);
817 dc.col = xmalloc(dc.collen * sizeof(Color));
820 for (i = 0; i < dc.collen; i++)
821 if (!xloadcolor(i, NULL, &dc.col[i])) {
823 die("could not allocate color '%s'\n", colorname[i]);
825 die("could not allocate color %d\n", i);
828 /* set alpha value of bg color */
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;
838 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
840 if (!BETWEEN(x, 0, dc.collen))
843 *r = dc.col[x].color.red >> 8;
844 *g = dc.col[x].color.green >> 8;
845 *b = dc.col[x].color.blue >> 8;
851 xsetcolorname(int x, const char *name)
855 if (!BETWEEN(x, 0, dc.collen))
858 if (!xloadcolor(x, name, &ncolor))
861 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
868 * Absolute coordinates.
871 xclear(int x1, int y1, int x2, int y2)
874 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
875 x1, y1, x2-x1, y2-y1);
881 XClassHint class = {opt_name ? opt_name : termname,
882 opt_class ? opt_class : termname};
883 XWMHints wm = {.flags = InputHint, .input = 1};
886 sizeh = XAllocSizeHints();
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;
898 sizeh->flags |= PMaxSize;
899 sizeh->min_width = sizeh->max_width = win.w;
900 sizeh->min_height = sizeh->max_height = win.h;
902 if (xw.gm & (XValue|YValue)) {
903 sizeh->flags |= USPosition | PWinGravity;
906 sizeh->win_gravity = xgeommasktogravity(xw.gm);
909 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
915 xgeommasktogravity(int mask)
917 switch (mask & (XNegative|YNegative)) {
919 return NorthWestGravity;
921 return NorthEastGravity;
923 return SouthWestGravity;
926 return SouthEastGravity;
930 xloadfont(Font *f, FcPattern *pattern)
932 FcPattern *configured;
936 int wantattr, haveattr;
939 * Manually configure instead of calling XftMatchFont
940 * so that we can use the configured pattern for
941 * "missing glyph" lookups.
943 configured = FcPatternDuplicate(pattern);
947 FcConfigSubstitute(NULL, configured, FcMatchPattern);
948 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
950 match = FcFontMatch(NULL, configured, &result);
952 FcPatternDestroy(configured);
956 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
957 FcPatternDestroy(configured);
958 FcPatternDestroy(match);
962 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
965 * Check if xft was unable to find a font with the appropriate
966 * slant but gave us one anyway. Try to mitigate.
968 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
969 &haveattr) != XftResultMatch) || haveattr < wantattr) {
971 fputs("font slant does not match\n", stderr);
975 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
977 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
978 &haveattr) != XftResultMatch) || haveattr != wantattr) {
980 fputs("font weight does not match\n", stderr);
984 XftTextExtentsUtf8(xw.dpy, f->match,
985 (const FcChar8 *) ascii_printable,
986 strlen(ascii_printable), &extents);
989 f->pattern = configured;
991 f->ascent = f->match->ascent;
992 f->descent = f->match->descent;
994 f->rbearing = f->match->max_advance_width;
996 f->height = f->ascent + f->descent;
997 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
1003 xloadfonts(const char *fontstr, double fontsize)
1008 if (fontstr[0] == '-')
1009 pattern = XftXlfdParse(fontstr, False, False);
1011 pattern = FcNameParse((const FcChar8 *)fontstr);
1014 die("can't open font %s\n", fontstr);
1017 FcPatternDel(pattern, FC_PIXEL_SIZE);
1018 FcPatternDel(pattern, FC_SIZE);
1019 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
1020 usedfontsize = fontsize;
1022 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
1024 usedfontsize = fontval;
1025 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
1030 * Default font size is 12, if none given. This is to
1031 * have a known usedfontsize value.
1033 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1036 defaultfontsize = usedfontsize;
1039 if (xloadfont(&dc.font, pattern))
1040 die("can't open font %s\n", fontstr);
1042 if (usedfontsize < 0) {
1043 FcPatternGetDouble(dc.font.match->pattern,
1044 FC_PIXEL_SIZE, 0, &fontval);
1045 usedfontsize = fontval;
1047 defaultfontsize = fontval;
1050 /* Setting character width and height. */
1051 win.cw = ceilf(dc.font.width * cwscale);
1052 win.ch = ceilf(dc.font.height * chscale);
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);
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);
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);
1069 FcPatternDestroy(pattern);
1073 xunloadfont(Font *f)
1075 XftFontClose(xw.dpy, f->match);
1076 FcPatternDestroy(f->pattern);
1078 FcFontSetDestroy(f->set);
1084 /* Free the loaded fonts in the font cache. */
1086 XftFontClose(xw.dpy, frc[--frclen].font);
1088 xunloadfont(&dc.font);
1089 xunloadfont(&dc.bfont);
1090 xunloadfont(&dc.ifont);
1091 xunloadfont(&dc.ibfont);
1095 ximopen(Display *dpy)
1097 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1098 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1100 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1101 if (xw.ime.xim == NULL)
1104 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1105 fprintf(stderr, "XSetIMValues: "
1106 "Could not set XNDestroyCallback.\n");
1108 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
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,
1118 if (xw.ime.xic == NULL)
1119 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1125 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1128 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1129 ximinstantiate, NULL);
1133 ximdestroy(XIM xim, XPointer client, XPointer call)
1136 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1137 ximinstantiate, NULL);
1138 XFree(xw.ime.spotlist);
1142 xicdestroy(XIC xim, XPointer client, XPointer call)
1149 xinit(int cols, int rows)
1154 pid_t thispid = getpid();
1155 XColor xmousefg, xmousebg;
1156 XWindowAttributes attr;
1159 if (!(xw.dpy = XOpenDisplay(NULL)))
1160 die("can't open display\n");
1161 xw.scr = XDefaultScreen(xw.dpy);
1163 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
1164 parent = XRootWindow(xw.dpy, xw.scr);
1167 XGetWindowAttributes(xw.dpy, parent, &attr);
1168 xw.depth = attr.depth;
1171 XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
1172 xw.vis = vis.visual;
1176 die("could not init fontconfig.\n");
1178 usedfont = (opt_font == NULL)? font : opt_font;
1179 xloadfonts(usedfont, 0);
1182 xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
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;
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;
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);
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);
1214 /* font spec buffer */
1215 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1217 /* Xft rendering context */
1218 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1221 if (!ximopen(xw.dpy)) {
1222 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1223 ximinstantiate, NULL);
1226 /* white cursor, black outline */
1227 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1228 XDefineCursor(xw.dpy, xw.win, cursor);
1230 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1231 xmousefg.red = 0xffff;
1232 xmousefg.green = 0xffff;
1233 xmousefg.blue = 0xffff;
1236 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1237 xmousebg.red = 0x0000;
1238 xmousebg.green = 0x0000;
1239 xmousebg.blue = 0x0000;
1242 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
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);
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);
1254 win.mode = MODE_NUMLOCK;
1257 XMapWindow(xw.dpy, xw.win);
1258 XSync(xw.dpy, False);
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;
1270 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
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;
1280 FcPattern *fcpattern, *fontpattern;
1281 FcFontSet *fcsets[] = { NULL };
1282 FcCharSet *fccharset;
1283 int i, f, numspecs = 0;
1285 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1286 /* Fetch rune and mode for current glyph. */
1288 mode = glyphs[i].mode;
1290 /* Skip dummy wide-character spacing. */
1291 if (mode == ATTR_WDUMMY)
1294 /* Determine font for glyph if different from previous glyph. */
1295 if (prevmode != mode) {
1298 frcflags = FRC_NORMAL;
1299 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1300 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1302 frcflags = FRC_ITALICBOLD;
1303 } else if (mode & ATTR_ITALIC) {
1305 frcflags = FRC_ITALIC;
1306 } else if (mode & ATTR_BOLD) {
1308 frcflags = FRC_BOLD;
1310 yp = winy + font->ascent;
1313 /* Lookup character index with default font. */
1314 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1316 specs[numspecs].font = font->match;
1317 specs[numspecs].glyph = glyphidx;
1318 specs[numspecs].x = (short)xp;
1319 specs[numspecs].y = (short)yp;
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)
1331 /* We got a default font for a not found glyph. */
1332 if (!glyphidx && frc[f].flags == frcflags
1333 && frc[f].unicodep == rune) {
1338 /* Nothing was found. Use fontconfig to find matching font. */
1341 font->set = FcFontSort(0, font->pattern,
1343 fcsets[0] = font->set;
1346 * Nothing was found in the cache. Now use
1347 * some dozen of Fontconfig calls to get the
1348 * font for one single character.
1350 * Xft and fontconfig are design failures.
1352 fcpattern = FcPatternDuplicate(font->pattern);
1353 fccharset = FcCharSetCreate();
1355 FcCharSetAddChar(fccharset, rune);
1356 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1358 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1360 FcConfigSubstitute(0, fcpattern,
1362 FcDefaultSubstitute(fcpattern);
1364 fontpattern = FcFontSetMatch(0, fcsets, 1,
1367 /* Allocate memory for the new cache entry. */
1368 if (frclen >= frccap) {
1370 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1373 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1375 if (!frc[frclen].font)
1376 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1378 frc[frclen].flags = frcflags;
1379 frc[frclen].unicodep = rune;
1381 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1386 FcPatternDestroy(fcpattern);
1387 FcCharSetDestroy(fccharset);
1390 specs[numspecs].font = frc[f].font;
1391 specs[numspecs].glyph = glyphidx;
1392 specs[numspecs].x = (short)xp;
1393 specs[numspecs].y = (short)yp;
1401 static int isSlopeRising (int x, int iPoint, int waveWidth)
1408 // Find absolute `x` of point
1409 x += iPoint * (waveWidth/2);
1411 // Find index of absolute wave
1412 int absSlope = x / ((float)waveWidth/2);
1414 return (absSlope % 2);
1417 static int getSlope (int x, int iPoint, int waveWidth)
1419 // Sizes: Caps are half width of slopes
1424 // <2-> <1> <---6---->
1426 // Find type of first point
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;
1436 firstType = UNDERCURL_SLOPE_BOTTOM_CAP;
1438 // Find type of given point
1439 int pointType = (iPoint % 4);
1440 pointType += firstType;
1447 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
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;
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;
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);
1473 fg = &dc.col[base.fg];
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);
1484 bg = &dc.col[base.bg];
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];
1491 if (IS_SET(MODE_REVERSE)) {
1492 if (fg == &dc.col[defaultfg]) {
1493 fg = &dc.col[defaultbg];
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,
1504 if (bg == &dc.col[defaultbg]) {
1505 bg = &dc.col[defaultfg];
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,
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);
1526 if (base.mode & ATTR_REVERSE) {
1532 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1535 if (base.mode & ATTR_INVISIBLE)
1538 /* Intelligent cleaning up of the borders. */
1540 xclear(0, (y == 0)? 0 : winy, borderpx,
1542 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
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)));
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);
1553 /* Clean up the region we want to draw to. */
1554 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1556 /* Set the clip region because Xft is sometimes dirty. */
1561 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1563 /* Render the glyphs. */
1564 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1566 /* Render underline and strikethrough. */
1567 if (base.mode & ATTR_UNDERLINE) {
1569 const int widthThreshold = 28; // +1 width every widthThreshold px of font
1570 int wlw = (win.ch / widthThreshold) + 1; // Wave Line Width
1572 if ((base.ucolor[0] >= 0) &&
1573 !(base.mode & ATTR_BLINK && win.mode & MODE_BLINK) &&
1574 !(base.mode & ATTR_INVISIBLE)
1576 // Special color for underline
1578 if (base.ucolor[1] < 0) {
1579 linecolor = dc.col[base.ucolor[0]].pixel;
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;
1592 // Foreground color for underline
1593 linecolor = fg->pixel;
1597 .foreground = linecolor,
1599 .line_style = LineSolid,
1600 .cap_style = CapNotLast
1603 GC ugc = XCreateGC(xw.dpy, XftDrawDrawable(xw.draw),
1604 GCForeground | GCLineWidth | GCLineStyle | GCCapStyle,
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;
1616 int wy = winy + win.ch - dc.font.descent;
1618 #if UNDERCURL_STYLE == UNDERCURL_CURLY
1620 int narcs = charlen * 2 + 1;
1621 XArc *arcs = xmalloc(sizeof(XArc) * narcs);
1624 for (i = 0; i < charlen-1; i++) {
1625 arcs[i*2] = (XArc) {
1626 .x = wx + win.cw * i + ww / 4,
1628 .width = win.cw / 2,
1633 arcs[i*2+1] = (XArc) {
1634 .x = wx + win.cw * i + ww * 0.75,
1643 arcs[i*2] = (XArc) {wx + ww * i + ww / 4, wy, ww / 2, wh,
1646 arcs[i*2+1] = (XArc) {wx + ww * i + ww * 0.75, wy, ceil(ww / 2.),
1647 wh, 180 * 64, 90 * 64};
1650 arcs[i*2] = (XArc) {wx - ww/4 - 1, wy, ceil(ww / 2.), wh, 270 * 64,
1653 XDrawArcs(xw.dpy, XftDrawDrawable(xw.draw), ugc, arcs, narcs);
1656 #elif UNDERCURL_STYLE == UNDERCURL_SPIKY
1657 // Make the underline corridor larger
1663 // Set the angle of the slope to 45°
1666 // Position of wave is independent of word, it's absolute
1667 wx = (wx / (ww/2)) * (ww/2);
1669 int marginStart = winx - wx;
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
1677 // Total length of underline
1678 float waveLength = 0;
1681 // We add an aditional slot in case we use a bonus point
1682 XPoint *points = xmalloc(sizeof(XPoint) * (npoints + 1));
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)
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)
1699 waveLength += (ww/2.f) - marginStart;
1701 // The rest of the points
1702 for (int i = 2; i < npoints-1; i++) {
1703 points[i] = (XPoint) {
1705 .y = (isSlopeRising(wx, i, ww))
1713 points[npoints-1] = (XPoint) {
1715 .y = (isSlopeRising(wx, npoints-1, ww))
1722 if (waveLength < width) { // Add a bonus point?
1723 int marginEnd = width - waveLength;
1724 points[npoints] = (XPoint) {
1726 .y = (isSlopeRising(wx, npoints, ww))
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);
1738 points[npoints-1].y += (marginEnd);
1742 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points, npoints,
1745 // Draw a second underline with an offset of 1 pixel
1746 if ( ((win.ch / (widthThreshold/2)) % 2)) {
1749 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points,
1750 npoints, CoordModePrevious);
1756 #else // UNDERCURL_CAPPED
1757 // Cap is half of wave width
1758 float capRatio = 0.5f;
1760 // Make the underline corridor larger
1763 // Set the angle of the slope to 45°
1765 ww *= 1 + capRatio; // Add a bit of width for the cap
1767 // Position of wave is independent of word, it's absolute
1768 wx = (wx / ww) * ww;
1771 switch(getSlope(winx, 0, ww)) {
1772 case UNDERCURL_SLOPE_ASCENDING:
1773 marginStart = winx - wx;
1775 case UNDERCURL_SLOPE_TOP_CAP:
1776 marginStart = winx - (wx + (ww * (2.f/6.f)));
1778 case UNDERCURL_SLOPE_DESCENDING:
1779 marginStart = winx - (wx + (ww * (3.f/6.f)));
1781 case UNDERCURL_SLOPE_BOTTOM_CAP:
1782 marginStart = winx - (wx + (ww * (5.f/6.f)));
1786 // Calculate number of points with floating precision
1787 float n = width; // Width of word in pixels
1789 n = (n / ww) * 4; // Number of points (./ \.)
1790 n += 2; // Add two last points
1791 int npoints = n; // Convert to int
1793 // Position of the pen to draw the lines
1798 XPoint *points = xmalloc(sizeof(XPoint) * (npoints + 1));
1800 // First point (Starts with the word bounds)
1802 switch (getSlope(winx, 0, ww)) {
1803 case UNDERCURL_SLOPE_ASCENDING:
1804 penY = wy + wh/2.f - marginStart;
1806 case UNDERCURL_SLOPE_TOP_CAP:
1809 case UNDERCURL_SLOPE_DESCENDING:
1810 penY = wy + marginStart;
1812 case UNDERCURL_SLOPE_BOTTOM_CAP:
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;
1825 case UNDERCURL_SLOPE_TOP_CAP:
1826 penX += ww * (2.f/6.f) - marginStart;
1827 penY += -wh/2.f + marginStart;
1829 case UNDERCURL_SLOPE_DESCENDING:
1830 penX += ww * (1.f/6.f) - marginStart;
1833 case UNDERCURL_SLOPE_BOTTOM_CAP:
1834 penX += ww * (2.f/6.f) - marginStart;
1835 penY += -marginStart + wh/2.f;
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);
1849 case UNDERCURL_SLOPE_TOP_CAP:
1850 penX += ww * (2.f/6.f);
1853 case UNDERCURL_SLOPE_BOTTOM_CAP:
1854 penX += ww * (2.f/6.f);
1863 float waveLength = penX - winx;
1864 if (waveLength < width) { // Add a bonus point?
1865 int marginEnd = width - waveLength;
1867 switch(getSlope(winx, npoints, ww)) {
1868 case UNDERCURL_SLOPE_ASCENDING:
1869 case UNDERCURL_SLOPE_DESCENDING:
1872 case UNDERCURL_SLOPE_TOP_CAP:
1875 case UNDERCURL_SLOPE_BOTTOM_CAP:
1880 points[npoints].x = penX;
1881 points[npoints].y = penY;
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;
1891 case UNDERCURL_SLOPE_BOTTOM_CAP:
1892 points[npoints-1].y -= marginEnd;
1900 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points, npoints,
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++)
1908 XDrawLines(xw.dpy, XftDrawDrawable(xw.draw), ugc, points,
1909 npoints, CoordModeOrigin);
1918 XFreeGC(xw.dpy, ugc);
1921 if (base.mode & ATTR_STRUCK) {
1922 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1926 /* Reset clip to none. */
1927 XftDrawSetClip(xw.draw, 0);
1931 xdrawglyph(Glyph g, int x, int y)
1934 XftGlyphFontSpec spec;
1936 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1937 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1941 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1946 /* remove the old cursor */
1947 if (selected(ox, oy))
1948 og.mode ^= ATTR_REVERSE;
1949 xdrawglyph(og, ox, oy);
1951 if (IS_SET(MODE_HIDE))
1955 * Select the right color for the right mode.
1957 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1959 if (IS_SET(MODE_REVERSE)) {
1960 g.mode |= ATTR_REVERSE;
1962 if (selected(cx, cy)) {
1963 drawcol = dc.col[defaultcs];
1966 drawcol = dc.col[defaultrcs];
1970 if (selected(cx, cy)) {
1974 /** this is the main part of the dynamic cursor color patch */
1980 * and this is the second part of the dynamic cursor color patch.
1981 * it handles the `drawcol` variable
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);
1990 drawcol = dc.col[g.bg];
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) */
2000 case 0: /* Blinking Block */
2001 case 1: /* Blinking Block (Default) */
2002 case 2: /* Steady Block */
2003 xdrawglyph(g, cx, cy);
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 - \
2011 win.cw, cursorthickness);
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);
2022 XftDrawRect(xw.draw, &drawcol,
2023 borderpx + cx * win.cw,
2024 borderpx + cy * win.ch,
2026 XftDrawRect(xw.draw, &drawcol,
2027 borderpx + cx * win.cw,
2028 borderpx + cy * win.ch,
2030 XftDrawRect(xw.draw, &drawcol,
2031 borderpx + (cx + 1) * win.cw - 1,
2032 borderpx + cy * win.ch,
2034 XftDrawRect(xw.draw, &drawcol,
2035 borderpx + cx * win.cw,
2036 borderpx + (cy + 1) * win.ch - 1,
2044 char buf[sizeof(long) * 8 + 1];
2046 snprintf(buf, sizeof(buf), "%lu", xw.win);
2047 setenv("WINDOWID", buf, 1);
2051 xseticontitle(char *p)
2054 DEFAULT(p, opt_title);
2056 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2059 XSetWMIconName(xw.dpy, xw.win, &prop);
2060 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
2068 DEFAULT(p, opt_title);
2070 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2073 XSetWMName(xw.dpy, xw.win, &prop);
2074 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
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);
2087 xdrawline(Line line, int x1, int y1, int x2)
2089 int i, x, ox, numspecs;
2091 XftGlyphFontSpec *specs = xw.specbuf;
2093 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
2095 for (x = x1; x < x2 && i < numspecs; x++) {
2097 if (new.mode == ATTR_WDUMMY)
2099 if (selected(x, y1))
2100 new.mode ^= ATTR_REVERSE;
2101 if (i > 0 && ATTRCMP(base, new)) {
2102 xdrawglyphfontspecs(specs, base, i, ox, y1);
2114 xdrawglyphfontspecs(specs, base, i, ox, y1);
2120 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
2122 XSetForeground(xw.dpy, dc.gc,
2123 dc.col[IS_SET(MODE_REVERSE)?
2124 defaultfg : defaultbg].pixel);
2128 xximspot(int x, int y)
2130 if (xw.ime.xic == NULL)
2133 xw.ime.spot.x = borderpx + x * win.cw;
2134 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
2136 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
2146 visibility(XEvent *ev)
2148 XVisibilityEvent *e = &ev->xvisibility;
2150 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
2156 win.mode &= ~MODE_VISIBLE;
2160 xsetpointermotion(int set)
2162 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
2163 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
2167 xsetmode(int set, unsigned int flags)
2169 int mode = win.mode;
2170 MODBIT(win.mode, set, flags);
2171 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
2176 xsetcursor(int cursor)
2178 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
2180 win.cursor = cursor;
2185 xseturgency(int add)
2187 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2189 MODBIT(h->flags, add, XUrgencyHint);
2190 XSetWMHints(xw.dpy, xw.win, h);
2197 if (!(IS_SET(MODE_FOCUSED)))
2200 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2206 XFocusChangeEvent *e = &ev->xfocus;
2208 if (e->mode == NotifyGrab)
2211 if (ev->type == FocusIn) {
2213 XSetICFocus(xw.ime.xic);
2214 win.mode |= MODE_FOCUSED;
2216 if (IS_SET(MODE_FOCUS))
2217 ttywrite("\033[I", 3, 0);
2220 XUnsetICFocus(xw.ime.xic);
2221 win.mode &= ~MODE_FOCUSED;
2222 if (IS_SET(MODE_FOCUS))
2223 ttywrite("\033[O", 3, 0);
2228 match(uint mask, uint state)
2230 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
2234 kmap(KeySym k, uint state)
2239 /* Check for mapped keys out of X11 function keys. */
2240 for (i = 0; i < LEN(mappedkeys); i++) {
2241 if (mappedkeys[i] == k)
2244 if (i == LEN(mappedkeys)) {
2245 if ((k & 0xFFFF) < 0xFD00)
2249 for (kp = key; kp < key + LEN(key); kp++) {
2253 if (!match(kp->mask, state))
2256 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
2258 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
2261 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
2273 XKeyEvent *e = &ev->xkey;
2275 char buf[64], *customkey;
2281 if (IS_SET(MODE_KBDLOCK))
2285 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
2287 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
2289 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
2290 if (ksym == bp->keysym && match(bp->mod, e->state)) {
2291 bp->func(&(bp->arg));
2296 /* 2. custom keys from config.h */
2297 if ((customkey = kmap(ksym, e->state))) {
2298 ttywrite(customkey, strlen(customkey), 1);
2302 /* 3. composed string from input method */
2305 if (len == 1 && e->state & Mod1Mask) {
2306 if (IS_SET(MODE_8BIT)) {
2309 len = utf8encode(c, buf);
2317 ttywrite(buf, len, 1);
2325 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
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;
2331 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2332 win.mode &= ~MODE_FOCUSED;
2334 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
2343 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
2346 cresize(e->xconfigure.width, e->xconfigure.height);
2350 int ttyread_pending();
2356 int w = win.w, h = win.h;
2358 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
2359 struct timespec seltv, *tv, now, lastblink, trigger;
2362 /* Waiting for window mapping */
2364 XNextEvent(xw.dpy, &ev);
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.
2370 if (XFilterEvent(&ev, None))
2372 if (ev.type == ConfigureNotify) {
2373 w = ev.xconfigure.width;
2374 h = ev.xconfigure.height;
2376 } while (ev.type != MapNotify);
2378 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
2381 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
2383 FD_SET(ttyfd, &rfd);
2386 if (XPending(xw.dpy) || ttyread_pending())
2387 timeout = 0; /* existing events might not set xfd */
2389 seltv.tv_sec = timeout / 1E3;
2390 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
2391 tv = timeout >= 0 ? &seltv : NULL;
2393 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
2396 die("select failed: %s\n", strerror(errno));
2398 clock_gettime(CLOCK_MONOTONIC, &now);
2400 int ttyin = FD_ISSET(ttyfd, &rfd) || ttyread_pending();
2405 while (XPending(xw.dpy)) {
2407 XNextEvent(xw.dpy, &ev);
2408 if (XFilterEvent(&ev, None))
2410 if (handler[ev.type])
2411 (handler[ev.type])(&ev);
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.
2430 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
2431 / maxlatency * minlatency;
2433 continue; /* we have time, try to find idle */
2436 if (tinsync(su_timeout)) {
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.
2444 timeout = minlatency;
2448 /* idle detected or maxlatency exhausted -> draw */
2450 if (blinktimeout && tattrset(ATTR_BLINK)) {
2451 timeout = blinktimeout - TIMEDIFF(now, lastblink);
2453 if (-timeout > blinktimeout) /* start visible */
2454 win.mode |= MODE_BLINK;
2455 win.mode ^= MODE_BLINK;
2456 tsetdirtattr(ATTR_BLINK);
2458 timeout = blinktimeout;
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);
2482 main(int argc, char *argv[])
2486 xsetcursor(cursorshape);
2493 opt_alpha = EARGF(usage());
2496 opt_class = EARGF(usage());
2503 opt_font = EARGF(usage());
2506 xw.gm = XParseGeometry(EARGF(usage()),
2507 &xw.l, &xw.t, &cols, &rows);
2513 opt_io = EARGF(usage());
2516 opt_line = EARGF(usage());
2519 opt_name = EARGF(usage());
2523 opt_title = EARGF(usage());
2526 opt_embed = EARGF(usage());
2529 die("%s " VERSION "\n", argv0);
2536 if (argc > 0) /* eat all remaining arguments */
2540 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2542 setlocale(LC_CTYPE, "");
2543 XSetLocaleModifiers("");
2544 cols = MAX(cols, 1);
2545 rows = MAX(rows, 1);