1 /* See LICENSE for license details. */
6 #include <sys/select.h>
10 #include <X11/Xatom.h>
12 #include <X11/Xutil.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
28 #define XEMBED_FOCUS_IN 4
29 #define XEMBED_FOCUS_OUT 5
32 #define TRUERED(x) (((x) & 0xff0000) >> 8)
33 #define TRUEGREEN(x) (((x) & 0xff00))
34 #define TRUEBLUE(x) (((x) & 0xff) << 8)
36 typedef XftDraw *Draw;
37 typedef XftColor Color;
39 /* Purely graphic info */
45 Atom xembed, wmdeletewin, netwmname, netwmpid;
50 XSetWindowAttributes attrs;
52 int isfixed; /* is fixed geometry? */
53 int l, t; /* left and top offset */
54 int gm; /* geometry mask */
80 Font font, bfont, ifont, ibfont;
84 static inline ushort sixd_to_16bit(int);
85 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
86 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
87 static void xdrawglyph(Glyph, int, int);
88 static void xclear(int, int, int, int);
89 static void xdrawcursor(void);
90 static int xgeommasktogravity(int);
91 static void xinit(void);
92 static int xloadfont(Font *, FcPattern *);
93 static void xloadfonts(char *, double);
94 static void xunloadfont(Font *);
95 static void xunloadfonts(void);
96 static void xsetenv(void);
97 static void xseturgency(int);
99 static void expose(XEvent *);
100 static void visibility(XEvent *);
101 static void unmap(XEvent *);
102 static void kpress(XEvent *);
103 static void cmessage(XEvent *);
104 static void resize(XEvent *);
105 static void focus(XEvent *);
106 static void brelease(XEvent *);
107 static void bpress(XEvent *);
108 static void bmotion(XEvent *);
109 static void propnotify(XEvent *);
110 static void selnotify(XEvent *);
111 static void selclear_(XEvent *);
112 static void selrequest(XEvent *);
114 static void selcopy(Time);
115 static void getbuttoninfo(XEvent *);
116 static void mousereport(XEvent *);
118 static void run(void);
119 static void usage(void);
121 static void (*handler[LASTEvent])(XEvent *) = {
123 [ClientMessage] = cmessage,
124 [ConfigureNotify] = resize,
125 [VisibilityNotify] = visibility,
126 [UnmapNotify] = unmap,
130 [MotionNotify] = bmotion,
131 [ButtonPress] = bpress,
132 [ButtonRelease] = brelease,
134 * Uncomment if you want the selection to disappear when you select something
135 * different in another window.
137 /* [SelectionClear] = selclear_, */
138 [SelectionNotify] = selnotify,
140 * PropertyNotify is only turned on when there is some INCR transfer happening
141 * for the selection retrieval.
143 [PropertyNotify] = propnotify,
144 [SelectionRequest] = selrequest,
150 static XSelection xsel;
152 /* Font Ring Cache */
166 /* Fontcache is an array now. A new font will be appended to the array. */
167 static Fontcache frc[16];
168 static int frclen = 0;
175 larg.f = usedfontsize + arg->f;
180 zoomabs(const Arg *arg)
183 xloadfonts(usedfont, arg->f);
191 zoomreset(const Arg *arg)
195 if (defaultfontsize > 0) {
196 larg.f = defaultfontsize;
202 getbuttoninfo(XEvent *e)
205 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
207 sel.alt = IS_SET(MODE_ALTSCREEN);
209 sel.oe.x = x2col(e->xbutton.x);
210 sel.oe.y = y2row(e->xbutton.y);
213 sel.type = SEL_REGULAR;
214 for (type = 1; type < selmaskslen; ++type) {
215 if (match(selmasks[type], state)) {
223 mousereport(XEvent *e)
225 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
226 button = e->xbutton.button, state = e->xbutton.state,
232 if (e->xbutton.type == MotionNotify) {
233 if (x == ox && y == oy)
235 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
237 /* MOUSE_MOTION: no reporting if no button is pressed */
238 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
241 button = oldbutton + 32;
245 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
252 if (e->xbutton.type == ButtonPress) {
256 } else if (e->xbutton.type == ButtonRelease) {
258 /* MODE_MOUSEX10: no button release reporting */
259 if (IS_SET(MODE_MOUSEX10))
261 if (button == 64 || button == 65)
266 if (!IS_SET(MODE_MOUSEX10)) {
267 button += ((state & ShiftMask ) ? 4 : 0)
268 + ((state & Mod4Mask ) ? 8 : 0)
269 + ((state & ControlMask) ? 16 : 0);
272 if (IS_SET(MODE_MOUSESGR)) {
273 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
275 e->xbutton.type == ButtonRelease ? 'm' : 'M');
276 } else if (x < 223 && y < 223) {
277 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
278 32+button, 32+x+1, 32+y+1);
292 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
297 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
298 if (e->xbutton.button == ms->b
299 && match(ms->mask, e->xbutton.state)) {
300 ttysend(ms->s, strlen(ms->s));
305 if (e->xbutton.button == Button1) {
306 clock_gettime(CLOCK_MONOTONIC, &now);
308 /* Clear previous selection, logically and visually. */
310 sel.mode = SEL_EMPTY;
311 sel.type = SEL_REGULAR;
312 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
313 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
316 * If the user clicks below predefined timeouts specific
317 * snapping behaviour is exposed.
319 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
320 sel.snap = SNAP_LINE;
321 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
322 sel.snap = SNAP_WORD;
329 sel.mode = SEL_READY;
330 tsetdirt(sel.nb.y, sel.ne.y);
331 sel.tclick2 = sel.tclick1;
339 xsetsel(getsel(), t);
343 propnotify(XEvent *e)
345 XPropertyEvent *xpev;
346 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
348 xpev = &e->xproperty;
349 if (xpev->state == PropertyNewValue &&
350 (xpev->atom == XA_PRIMARY ||
351 xpev->atom == clipboard)) {
359 ulong nitems, ofs, rem;
361 uchar *data, *last, *repl;
362 Atom type, incratom, property;
364 incratom = XInternAtom(xw.dpy, "INCR", 0);
367 if (e->type == SelectionNotify) {
368 property = e->xselection.property;
369 } else if(e->type == PropertyNotify) {
370 property = e->xproperty.atom;
374 if (property == None)
378 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
379 BUFSIZ/4, False, AnyPropertyType,
380 &type, &format, &nitems, &rem,
382 fprintf(stderr, "Clipboard allocation failed\n");
386 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
388 * If there is some PropertyNotify with no data, then
389 * this is the signal of the selection owner that all
390 * data has been transferred. We won't need to receive
391 * PropertyNotify events anymore.
393 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
394 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
398 if (type == incratom) {
400 * Activate the PropertyNotify events so we receive
401 * when the selection owner does send us the next
404 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
405 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
409 * Deleting the property is the transfer start signal.
411 XDeleteProperty(xw.dpy, xw.win, (int)property);
417 * Line endings are inconsistent in the terminal and GUI world
418 * copy and pasting. When receiving some selection data,
419 * replace all '\n' with '\r'.
420 * FIXME: Fix the computer world.
423 last = data + nitems * format / 8;
424 while ((repl = memchr(repl, '\n', last - repl))) {
428 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
429 ttywrite("\033[200~", 6);
430 ttysend((char *)data, nitems * format / 8);
431 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
432 ttywrite("\033[201~", 6);
434 /* number of 32-bit chunks returned */
435 ofs += nitems * format / 32;
439 * Deleting the property again tells the selection owner to send the
440 * next data chunk in the property.
442 XDeleteProperty(xw.dpy, xw.win, (int)property);
448 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
449 xw.win, CurrentTime);
457 if (sel.clipboard != NULL)
460 if (sel.primary != NULL) {
461 sel.clipboard = xstrdup(sel.primary);
462 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
463 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
472 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
473 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
474 xw.win, CurrentTime);
484 selrequest(XEvent *e)
486 XSelectionRequestEvent *xsre;
488 Atom xa_targets, string, clipboard;
491 xsre = (XSelectionRequestEvent *) e;
492 xev.type = SelectionNotify;
493 xev.requestor = xsre->requestor;
494 xev.selection = xsre->selection;
495 xev.target = xsre->target;
496 xev.time = xsre->time;
497 if (xsre->property == None)
498 xsre->property = xsre->target;
503 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
504 if (xsre->target == xa_targets) {
505 /* respond with the supported type */
506 string = xsel.xtarget;
507 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
508 XA_ATOM, 32, PropModeReplace,
509 (uchar *) &string, 1);
510 xev.property = xsre->property;
511 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
513 * xith XA_STRING non ascii characters may be incorrect in the
514 * requestor. It is not our problem, use utf8.
516 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
517 if (xsre->selection == XA_PRIMARY) {
518 seltext = sel.primary;
519 } else if (xsre->selection == clipboard) {
520 seltext = sel.clipboard;
523 "Unhandled clipboard selection 0x%lx\n",
527 if (seltext != NULL) {
528 XChangeProperty(xsre->display, xsre->requestor,
529 xsre->property, xsre->target,
531 (uchar *)seltext, strlen(seltext));
532 xev.property = xsre->property;
536 /* all done, send a notification to the listener */
537 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
538 fprintf(stderr, "Error sending SelectionNotify event\n");
542 xsetsel(char *str, Time t)
547 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
548 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
555 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
560 if (e->xbutton.button == Button2) {
562 } else if (e->xbutton.button == Button1) {
563 if (sel.mode == SEL_READY) {
565 selcopy(e->xbutton.time);
569 tsetdirt(sel.nb.y, sel.ne.y);
576 int oldey, oldex, oldsby, oldsey;
578 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
586 sel.mode = SEL_READY;
593 if (oldey != sel.oe.y || oldex != sel.oe.x)
594 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
598 xresize(int col, int row)
600 win.tw = MAX(1, col * win.cw);
601 win.th = MAX(1, row * win.ch);
603 XFreePixmap(xw.dpy, xw.buf);
604 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
605 DefaultDepth(xw.dpy, xw.scr));
606 XftDrawChange(xw.draw, xw.buf);
607 xclear(0, 0, win.w, win.h);
613 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
617 xloadcolor(int i, const char *name, Color *ncolor)
619 XRenderColor color = { .alpha = 0xffff };
622 if (BETWEEN(i, 16, 255)) { /* 256 color */
623 if (i < 6*6*6+16) { /* same colors as xterm */
624 color.red = sixd_to_16bit( ((i-16)/36)%6 );
625 color.green = sixd_to_16bit( ((i-16)/6) %6 );
626 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
627 } else { /* greyscale */
628 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
629 color.green = color.blue = color.red;
631 return XftColorAllocValue(xw.dpy, xw.vis,
632 xw.cmap, &color, ncolor);
637 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
647 dc.collen = MAX(colornamelen, 256);
648 dc.col = xmalloc(dc.collen * sizeof(Color));
651 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
652 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
655 for (i = 0; i < dc.collen; i++)
656 if (!xloadcolor(i, NULL, &dc.col[i])) {
658 die("Could not allocate color '%s'\n", colorname[i]);
660 die("Could not allocate color %d\n", i);
666 xsetcolorname(int x, const char *name)
670 if (!BETWEEN(x, 0, dc.collen))
674 if (!xloadcolor(x, name, &ncolor))
677 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
684 * Absolute coordinates.
687 xclear(int x1, int y1, int x2, int y2)
690 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
691 x1, y1, x2-x1, y2-y1);
697 XClassHint class = {opt_name ? opt_name : termname,
698 opt_class ? opt_class : termname};
699 XWMHints wm = {.flags = InputHint, .input = 1};
700 XSizeHints *sizeh = NULL;
702 sizeh = XAllocSizeHints();
704 sizeh->flags = PSize | PResizeInc | PBaseSize;
705 sizeh->height = win.h;
706 sizeh->width = win.w;
707 sizeh->height_inc = win.ch;
708 sizeh->width_inc = win.cw;
709 sizeh->base_height = 2 * borderpx;
710 sizeh->base_width = 2 * borderpx;
712 sizeh->flags |= PMaxSize | PMinSize;
713 sizeh->min_width = sizeh->max_width = win.w;
714 sizeh->min_height = sizeh->max_height = win.h;
716 if (xw.gm & (XValue|YValue)) {
717 sizeh->flags |= USPosition | PWinGravity;
720 sizeh->win_gravity = xgeommasktogravity(xw.gm);
723 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
729 xgeommasktogravity(int mask)
731 switch (mask & (XNegative|YNegative)) {
733 return NorthWestGravity;
735 return NorthEastGravity;
737 return SouthWestGravity;
740 return SouthEastGravity;
744 xloadfont(Font *f, FcPattern *pattern)
746 FcPattern *configured;
750 int wantattr, haveattr;
753 * Manually configure instead of calling XftMatchFont
754 * so that we can use the configured pattern for
755 * "missing glyph" lookups.
757 configured = FcPatternDuplicate(pattern);
761 FcConfigSubstitute(NULL, configured, FcMatchPattern);
762 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
764 match = FcFontMatch(NULL, configured, &result);
766 FcPatternDestroy(configured);
770 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
771 FcPatternDestroy(configured);
772 FcPatternDestroy(match);
776 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
779 * Check if xft was unable to find a font with the appropriate
780 * slant but gave us one anyway. Try to mitigate.
782 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
783 &haveattr) != XftResultMatch) || haveattr < wantattr) {
785 fputs("st: font slant does not match\n", stderr);
789 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
791 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
792 &haveattr) != XftResultMatch) || haveattr != wantattr) {
794 fputs("st: font weight does not match\n", stderr);
798 XftTextExtentsUtf8(xw.dpy, f->match,
799 (const FcChar8 *) ascii_printable,
800 strlen(ascii_printable), &extents);
803 f->pattern = configured;
805 f->ascent = f->match->ascent;
806 f->descent = f->match->descent;
808 f->rbearing = f->match->max_advance_width;
810 f->height = f->ascent + f->descent;
811 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
817 xloadfonts(char *fontstr, double fontsize)
823 if (fontstr[0] == '-') {
824 pattern = XftXlfdParse(fontstr, False, False);
826 pattern = FcNameParse((FcChar8 *)fontstr);
830 die("st: can't open font %s\n", fontstr);
833 FcPatternDel(pattern, FC_PIXEL_SIZE);
834 FcPatternDel(pattern, FC_SIZE);
835 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
836 usedfontsize = fontsize;
838 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
840 usedfontsize = fontval;
841 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
846 * Default font size is 12, if none given. This is to
847 * have a known usedfontsize value.
849 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
852 defaultfontsize = usedfontsize;
855 if (xloadfont(&dc.font, pattern))
856 die("st: can't open font %s\n", fontstr);
858 if (usedfontsize < 0) {
859 FcPatternGetDouble(dc.font.match->pattern,
860 FC_PIXEL_SIZE, 0, &fontval);
861 usedfontsize = fontval;
863 defaultfontsize = fontval;
866 /* Setting character width and height. */
867 win.cw = ceilf(dc.font.width * cwscale);
868 win.ch = ceilf(dc.font.height * chscale);
870 FcPatternDel(pattern, FC_SLANT);
871 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
872 if (xloadfont(&dc.ifont, pattern))
873 die("st: can't open font %s\n", fontstr);
875 FcPatternDel(pattern, FC_WEIGHT);
876 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
877 if (xloadfont(&dc.ibfont, pattern))
878 die("st: can't open font %s\n", fontstr);
880 FcPatternDel(pattern, FC_SLANT);
881 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
882 if (xloadfont(&dc.bfont, pattern))
883 die("st: can't open font %s\n", fontstr);
885 FcPatternDestroy(pattern);
891 XftFontClose(xw.dpy, f->match);
892 FcPatternDestroy(f->pattern);
894 FcFontSetDestroy(f->set);
900 /* Free the loaded fonts in the font cache. */
902 XftFontClose(xw.dpy, frc[--frclen].font);
904 xunloadfont(&dc.font);
905 xunloadfont(&dc.bfont);
906 xunloadfont(&dc.ifont);
907 xunloadfont(&dc.ibfont);
916 pid_t thispid = getpid();
917 XColor xmousefg, xmousebg;
919 if (!(xw.dpy = XOpenDisplay(NULL)))
920 die("Can't open display\n");
921 xw.scr = XDefaultScreen(xw.dpy);
922 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
926 die("Could not init fontconfig.\n");
928 usedfont = (opt_font == NULL)? font : opt_font;
929 xloadfonts(usedfont, 0);
932 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
935 /* adjust fixed window geometry */
936 win.w = 2 * borderpx + term.col * win.cw;
937 win.h = 2 * borderpx + term.row * win.ch;
938 if (xw.gm & XNegative)
939 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
940 if (xw.gm & YNegative)
941 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
944 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
945 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
946 xw.attrs.bit_gravity = NorthWestGravity;
947 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
948 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
949 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
950 xw.attrs.colormap = xw.cmap;
952 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
953 parent = XRootWindow(xw.dpy, xw.scr);
954 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
955 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
956 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
957 | CWEventMask | CWColormap, &xw.attrs);
959 memset(&gcvalues, 0, sizeof(gcvalues));
960 gcvalues.graphics_exposures = False;
961 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
963 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
964 DefaultDepth(xw.dpy, xw.scr));
965 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
966 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
968 /* Xft rendering context */
969 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
972 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
973 XSetLocaleModifiers("@im=local");
974 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
975 XSetLocaleModifiers("@im=");
976 if ((xw.xim = XOpenIM(xw.dpy,
977 NULL, NULL, NULL)) == NULL) {
978 die("XOpenIM failed. Could not open input"
983 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
984 | XIMStatusNothing, XNClientWindow, xw.win,
985 XNFocusWindow, xw.win, NULL);
987 die("XCreateIC failed. Could not obtain input method.\n");
989 /* white cursor, black outline */
990 cursor = XCreateFontCursor(xw.dpy, mouseshape);
991 XDefineCursor(xw.dpy, xw.win, cursor);
993 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
994 xmousefg.red = 0xffff;
995 xmousefg.green = 0xffff;
996 xmousefg.blue = 0xffff;
999 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1000 xmousebg.red = 0x0000;
1001 xmousebg.green = 0x0000;
1002 xmousebg.blue = 0x0000;
1005 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1007 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1008 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1009 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1010 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1012 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1013 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1014 PropModeReplace, (uchar *)&thispid, 1);
1017 XMapWindow(xw.dpy, xw.win);
1019 XSync(xw.dpy, False);
1021 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1022 if (xsel.xtarget == None)
1023 xsel.xtarget = XA_STRING;
1027 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1029 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1030 ushort mode, prevmode = USHRT_MAX;
1031 Font *font = &dc.font;
1032 int frcflags = FRC_NORMAL;
1033 float runewidth = win.cw;
1037 FcPattern *fcpattern, *fontpattern;
1038 FcFontSet *fcsets[] = { NULL };
1039 FcCharSet *fccharset;
1040 int i, f, numspecs = 0;
1042 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1043 /* Fetch rune and mode for current glyph. */
1045 mode = glyphs[i].mode;
1047 /* Skip dummy wide-character spacing. */
1048 if (mode == ATTR_WDUMMY)
1051 /* Determine font for glyph if different from previous glyph. */
1052 if (prevmode != mode) {
1055 frcflags = FRC_NORMAL;
1056 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1057 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1059 frcflags = FRC_ITALICBOLD;
1060 } else if (mode & ATTR_ITALIC) {
1062 frcflags = FRC_ITALIC;
1063 } else if (mode & ATTR_BOLD) {
1065 frcflags = FRC_BOLD;
1067 yp = winy + font->ascent;
1070 /* Lookup character index with default font. */
1071 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1073 specs[numspecs].font = font->match;
1074 specs[numspecs].glyph = glyphidx;
1075 specs[numspecs].x = (short)xp;
1076 specs[numspecs].y = (short)yp;
1082 /* Fallback on font cache, search the font cache for match. */
1083 for (f = 0; f < frclen; f++) {
1084 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1085 /* Everything correct. */
1086 if (glyphidx && frc[f].flags == frcflags)
1088 /* We got a default font for a not found glyph. */
1089 if (!glyphidx && frc[f].flags == frcflags
1090 && frc[f].unicodep == rune) {
1095 /* Nothing was found. Use fontconfig to find matching font. */
1098 font->set = FcFontSort(0, font->pattern,
1100 fcsets[0] = font->set;
1103 * Nothing was found in the cache. Now use
1104 * some dozen of Fontconfig calls to get the
1105 * font for one single character.
1107 * Xft and fontconfig are design failures.
1109 fcpattern = FcPatternDuplicate(font->pattern);
1110 fccharset = FcCharSetCreate();
1112 FcCharSetAddChar(fccharset, rune);
1113 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1115 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1117 FcConfigSubstitute(0, fcpattern,
1119 FcDefaultSubstitute(fcpattern);
1121 fontpattern = FcFontSetMatch(0, fcsets, 1,
1125 * Overwrite or create the new cache entry.
1127 if (frclen >= LEN(frc)) {
1128 frclen = LEN(frc) - 1;
1129 XftFontClose(xw.dpy, frc[frclen].font);
1130 frc[frclen].unicodep = 0;
1133 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1135 if (!frc[frclen].font)
1136 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1138 frc[frclen].flags = frcflags;
1139 frc[frclen].unicodep = rune;
1141 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1146 FcPatternDestroy(fcpattern);
1147 FcCharSetDestroy(fccharset);
1150 specs[numspecs].font = frc[f].font;
1151 specs[numspecs].glyph = glyphidx;
1152 specs[numspecs].x = (short)xp;
1153 specs[numspecs].y = (short)yp;
1162 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1164 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1165 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1166 width = charlen * win.cw;
1167 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1168 XRenderColor colfg, colbg;
1171 /* Fallback on color display for attributes not supported by the font */
1172 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1173 if (dc.ibfont.badslant || dc.ibfont.badweight)
1174 base.fg = defaultattr;
1175 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1176 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1177 base.fg = defaultattr;
1180 if (IS_TRUECOL(base.fg)) {
1181 colfg.alpha = 0xffff;
1182 colfg.red = TRUERED(base.fg);
1183 colfg.green = TRUEGREEN(base.fg);
1184 colfg.blue = TRUEBLUE(base.fg);
1185 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1188 fg = &dc.col[base.fg];
1191 if (IS_TRUECOL(base.bg)) {
1192 colbg.alpha = 0xffff;
1193 colbg.green = TRUEGREEN(base.bg);
1194 colbg.red = TRUERED(base.bg);
1195 colbg.blue = TRUEBLUE(base.bg);
1196 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1199 bg = &dc.col[base.bg];
1202 /* Change basic system colors [0-7] to bright system colors [8-15] */
1203 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1204 fg = &dc.col[base.fg + 8];
1206 if (IS_SET(MODE_REVERSE)) {
1207 if (fg == &dc.col[defaultfg]) {
1208 fg = &dc.col[defaultbg];
1210 colfg.red = ~fg->color.red;
1211 colfg.green = ~fg->color.green;
1212 colfg.blue = ~fg->color.blue;
1213 colfg.alpha = fg->color.alpha;
1214 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1219 if (bg == &dc.col[defaultbg]) {
1220 bg = &dc.col[defaultfg];
1222 colbg.red = ~bg->color.red;
1223 colbg.green = ~bg->color.green;
1224 colbg.blue = ~bg->color.blue;
1225 colbg.alpha = bg->color.alpha;
1226 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1232 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1233 colfg.red = fg->color.red / 2;
1234 colfg.green = fg->color.green / 2;
1235 colfg.blue = fg->color.blue / 2;
1236 colfg.alpha = fg->color.alpha;
1237 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1242 if (base.mode & ATTR_REVERSE) {
1248 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1251 if (base.mode & ATTR_INVISIBLE)
1254 /* Intelligent cleaning up of the borders. */
1256 xclear(0, (y == 0)? 0 : winy, borderpx,
1257 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1259 if (x + charlen >= term.col) {
1260 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1261 ((y >= term.row-1)? win.h : (winy + win.ch)));
1264 xclear(winx, 0, winx + width, borderpx);
1265 if (y == term.row-1)
1266 xclear(winx, winy + win.ch, winx + width, win.h);
1268 /* Clean up the region we want to draw to. */
1269 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1271 /* Set the clip region because Xft is sometimes dirty. */
1276 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1278 /* Render the glyphs. */
1279 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1281 /* Render underline and strikethrough. */
1282 if (base.mode & ATTR_UNDERLINE) {
1283 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1287 if (base.mode & ATTR_STRUCK) {
1288 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1292 /* Reset clip to none. */
1293 XftDrawSetClip(xw.draw, 0);
1297 xdrawglyph(Glyph g, int x, int y)
1300 XftGlyphFontSpec spec;
1302 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1303 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1309 static int oldx = 0, oldy = 0;
1311 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1312 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1315 LIMIT(oldx, 0, term.col-1);
1316 LIMIT(oldy, 0, term.row-1);
1320 /* adjust position if in dummy */
1321 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1323 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1326 /* remove the old cursor */
1327 og = term.line[oldy][oldx];
1328 if (ena_sel && selected(oldx, oldy))
1329 og.mode ^= ATTR_REVERSE;
1330 xdrawglyph(og, oldx, oldy);
1332 g.u = term.line[term.c.y][term.c.x].u;
1333 g.mode |= term.line[term.c.y][term.c.x].mode &
1334 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1337 * Select the right color for the right mode.
1339 if (IS_SET(MODE_REVERSE)) {
1340 g.mode |= ATTR_REVERSE;
1342 if (ena_sel && selected(term.c.x, term.c.y)) {
1343 drawcol = dc.col[defaultcs];
1346 drawcol = dc.col[defaultrcs];
1350 if (ena_sel && selected(term.c.x, term.c.y)) {
1351 drawcol = dc.col[defaultrcs];
1355 drawcol = dc.col[defaultcs];
1359 if (IS_SET(MODE_HIDE))
1362 /* draw the new one */
1363 if (win.state & WIN_FOCUSED) {
1364 switch (win.cursor) {
1365 case 7: /* st extension: snowman */
1366 utf8decode("☃", &g.u, UTF_SIZ);
1367 case 0: /* Blinking Block */
1368 case 1: /* Blinking Block (Default) */
1369 case 2: /* Steady Block */
1370 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1371 xdrawglyph(g, term.c.x, term.c.y);
1373 case 3: /* Blinking Underline */
1374 case 4: /* Steady Underline */
1375 XftDrawRect(xw.draw, &drawcol,
1376 borderpx + curx * win.cw,
1377 borderpx + (term.c.y + 1) * win.ch - \
1379 win.cw, cursorthickness);
1381 case 5: /* Blinking bar */
1382 case 6: /* Steady bar */
1383 XftDrawRect(xw.draw, &drawcol,
1384 borderpx + curx * win.cw,
1385 borderpx + term.c.y * win.ch,
1386 cursorthickness, win.ch);
1390 XftDrawRect(xw.draw, &drawcol,
1391 borderpx + curx * win.cw,
1392 borderpx + term.c.y * win.ch,
1394 XftDrawRect(xw.draw, &drawcol,
1395 borderpx + curx * win.cw,
1396 borderpx + term.c.y * win.ch,
1398 XftDrawRect(xw.draw, &drawcol,
1399 borderpx + (curx + 1) * win.cw - 1,
1400 borderpx + term.c.y * win.ch,
1402 XftDrawRect(xw.draw, &drawcol,
1403 borderpx + curx * win.cw,
1404 borderpx + (term.c.y + 1) * win.ch - 1,
1407 oldx = curx, oldy = term.c.y;
1413 char buf[sizeof(long) * 8 + 1];
1415 snprintf(buf, sizeof(buf), "%lu", xw.win);
1416 setenv("WINDOWID", buf, 1);
1424 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1426 XSetWMName(xw.dpy, xw.win, &prop);
1427 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1434 drawregion(0, 0, term.col, term.row);
1435 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1437 XSetForeground(xw.dpy, dc.gc,
1438 dc.col[IS_SET(MODE_REVERSE)?
1439 defaultfg : defaultbg].pixel);
1443 drawregion(int x1, int y1, int x2, int y2)
1445 int i, x, y, ox, numspecs;
1447 XftGlyphFontSpec *specs;
1448 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1450 if (!(win.state & WIN_VISIBLE))
1453 for (y = y1; y < y2; y++) {
1459 specs = term.specbuf;
1460 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1463 for (x = x1; x < x2 && i < numspecs; x++) {
1464 new = term.line[y][x];
1465 if (new.mode == ATTR_WDUMMY)
1467 if (ena_sel && selected(x, y))
1468 new.mode ^= ATTR_REVERSE;
1469 if (i > 0 && ATTRCMP(base, new)) {
1470 xdrawglyphfontspecs(specs, base, i, ox, y);
1482 xdrawglyphfontspecs(specs, base, i, ox, y);
1494 visibility(XEvent *ev)
1496 XVisibilityEvent *e = &ev->xvisibility;
1498 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1504 win.state &= ~WIN_VISIBLE;
1508 xsetpointermotion(int set)
1510 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1511 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1515 xseturgency(int add)
1517 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1519 MODBIT(h->flags, add, XUrgencyHint);
1520 XSetWMHints(xw.dpy, xw.win, h);
1527 if (!(win.state & WIN_FOCUSED))
1530 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1536 XFocusChangeEvent *e = &ev->xfocus;
1538 if (e->mode == NotifyGrab)
1541 if (ev->type == FocusIn) {
1542 XSetICFocus(xw.xic);
1543 win.state |= WIN_FOCUSED;
1545 if (IS_SET(MODE_FOCUS))
1546 ttywrite("\033[I", 3);
1548 XUnsetICFocus(xw.xic);
1549 win.state &= ~WIN_FOCUSED;
1550 if (IS_SET(MODE_FOCUS))
1551 ttywrite("\033[O", 3);
1558 XKeyEvent *e = &ev->xkey;
1560 char buf[32], *customkey;
1566 if (IS_SET(MODE_KBDLOCK))
1569 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1571 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1572 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1573 bp->func(&(bp->arg));
1578 /* 2. custom keys from config.h */
1579 if ((customkey = kmap(ksym, e->state))) {
1580 ttysend(customkey, strlen(customkey));
1584 /* 3. composed string from input method */
1587 if (len == 1 && e->state & Mod1Mask) {
1588 if (IS_SET(MODE_8BIT)) {
1591 len = utf8encode(c, buf);
1608 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1610 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1611 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1612 win.state |= WIN_FOCUSED;
1614 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1615 win.state &= ~WIN_FOCUSED;
1617 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1618 /* Send SIGHUP to shell */
1627 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1630 cresize(e->xconfigure.width, e->xconfigure.height);
1638 int w = win.w, h = win.h;
1640 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1641 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1644 /* Waiting for window mapping */
1646 XNextEvent(xw.dpy, &ev);
1648 * This XFilterEvent call is required because of XOpenIM. It
1649 * does filter out the key event and some client message for
1650 * the input method too.
1652 if (XFilterEvent(&ev, None))
1654 if (ev.type == ConfigureNotify) {
1655 w = ev.xconfigure.width;
1656 h = ev.xconfigure.height;
1658 } while (ev.type != MapNotify);
1664 clock_gettime(CLOCK_MONOTONIC, &last);
1667 for (xev = actionfps;;) {
1669 FD_SET(cmdfd, &rfd);
1672 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1675 die("select failed: %s\n", strerror(errno));
1677 if (FD_ISSET(cmdfd, &rfd)) {
1680 blinkset = tattrset(ATTR_BLINK);
1682 MODBIT(term.mode, 0, MODE_BLINK);
1686 if (FD_ISSET(xfd, &rfd))
1689 clock_gettime(CLOCK_MONOTONIC, &now);
1690 drawtimeout.tv_sec = 0;
1691 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1695 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1696 tsetdirtattr(ATTR_BLINK);
1697 term.mode ^= MODE_BLINK;
1701 deltatime = TIMEDIFF(now, last);
1702 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1708 while (XPending(xw.dpy)) {
1709 XNextEvent(xw.dpy, &ev);
1710 if (XFilterEvent(&ev, None))
1712 if (handler[ev.type])
1713 (handler[ev.type])(&ev);
1719 if (xev && !FD_ISSET(xfd, &rfd))
1721 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1723 if (TIMEDIFF(now, lastblink) \
1725 drawtimeout.tv_nsec = 1000;
1727 drawtimeout.tv_nsec = (1E6 * \
1732 drawtimeout.tv_sec = \
1733 drawtimeout.tv_nsec / 1E9;
1734 drawtimeout.tv_nsec %= (long)1E9;
1746 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1747 " [-n name] [-o file]\n"
1748 " [-T title] [-t title] [-w windowid]"
1749 " [[-e] command [args ...]]\n"
1750 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1751 " [-n name] [-o file]\n"
1752 " [-T title] [-t title] [-w windowid] -l line"
1753 " [stty_args ...]\n", argv0, argv0);
1757 main(int argc, char *argv[])
1761 win.cursor = cursorshape;
1768 opt_class = EARGF(usage());
1775 opt_font = EARGF(usage());
1778 xw.gm = XParseGeometry(EARGF(usage()),
1779 &xw.l, &xw.t, &cols, &rows);
1785 opt_io = EARGF(usage());
1788 opt_line = EARGF(usage());
1791 opt_name = EARGF(usage());
1795 opt_title = EARGF(usage());
1798 opt_embed = EARGF(usage());
1801 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1809 /* eat all remaining arguments */
1811 if (!opt_title && !opt_line)
1812 opt_title = basename(xstrdup(argv[0]));
1814 setlocale(LC_CTYPE, "");
1815 XSetLocaleModifiers("");
1816 tnew(MAX(cols, 1), MAX(rows, 1));