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 xunloadfont(Font *);
94 static void xsetenv(void);
96 static void expose(XEvent *);
97 static void visibility(XEvent *);
98 static void unmap(XEvent *);
99 static void kpress(XEvent *);
100 static void cmessage(XEvent *);
101 static void resize(XEvent *);
102 static void focus(XEvent *);
103 static void brelease(XEvent *);
104 static void bpress(XEvent *);
105 static void bmotion(XEvent *);
106 static void propnotify(XEvent *);
107 static void selnotify(XEvent *);
108 static void selclear_(XEvent *);
109 static void selrequest(XEvent *);
111 static void selcopy(Time);
112 static void getbuttoninfo(XEvent *);
113 static void mousereport(XEvent *);
115 static void run(void);
116 static void usage(void);
118 static void (*handler[LASTEvent])(XEvent *) = {
120 [ClientMessage] = cmessage,
121 [ConfigureNotify] = resize,
122 [VisibilityNotify] = visibility,
123 [UnmapNotify] = unmap,
127 [MotionNotify] = bmotion,
128 [ButtonPress] = bpress,
129 [ButtonRelease] = brelease,
131 * Uncomment if you want the selection to disappear when you select something
132 * different in another window.
134 /* [SelectionClear] = selclear_, */
135 [SelectionNotify] = selnotify,
137 * PropertyNotify is only turned on when there is some INCR transfer happening
138 * for the selection retrieval.
140 [PropertyNotify] = propnotify,
141 [SelectionRequest] = selrequest,
147 static XSelection xsel;
149 /* Font Ring Cache */
163 /* Fontcache is an array now. A new font will be appended to the array. */
164 static Fontcache frc[16];
165 static int frclen = 0;
168 getbuttoninfo(XEvent *e)
171 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
173 sel.alt = IS_SET(MODE_ALTSCREEN);
175 sel.oe.x = x2col(e->xbutton.x);
176 sel.oe.y = y2row(e->xbutton.y);
179 sel.type = SEL_REGULAR;
180 for (type = 1; type < selmaskslen; ++type) {
181 if (match(selmasks[type], state)) {
189 mousereport(XEvent *e)
191 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
192 button = e->xbutton.button, state = e->xbutton.state,
198 if (e->xbutton.type == MotionNotify) {
199 if (x == ox && y == oy)
201 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
203 /* MOUSE_MOTION: no reporting if no button is pressed */
204 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
207 button = oldbutton + 32;
211 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
218 if (e->xbutton.type == ButtonPress) {
222 } else if (e->xbutton.type == ButtonRelease) {
224 /* MODE_MOUSEX10: no button release reporting */
225 if (IS_SET(MODE_MOUSEX10))
227 if (button == 64 || button == 65)
232 if (!IS_SET(MODE_MOUSEX10)) {
233 button += ((state & ShiftMask ) ? 4 : 0)
234 + ((state & Mod4Mask ) ? 8 : 0)
235 + ((state & ControlMask) ? 16 : 0);
238 if (IS_SET(MODE_MOUSESGR)) {
239 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
241 e->xbutton.type == ButtonRelease ? 'm' : 'M');
242 } else if (x < 223 && y < 223) {
243 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
244 32+button, 32+x+1, 32+y+1);
258 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
263 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
264 if (e->xbutton.button == ms->b
265 && match(ms->mask, e->xbutton.state)) {
266 ttysend(ms->s, strlen(ms->s));
271 if (e->xbutton.button == Button1) {
272 clock_gettime(CLOCK_MONOTONIC, &now);
274 /* Clear previous selection, logically and visually. */
276 sel.mode = SEL_EMPTY;
277 sel.type = SEL_REGULAR;
278 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
279 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
282 * If the user clicks below predefined timeouts specific
283 * snapping behaviour is exposed.
285 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
286 sel.snap = SNAP_LINE;
287 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
288 sel.snap = SNAP_WORD;
295 sel.mode = SEL_READY;
296 tsetdirt(sel.nb.y, sel.ne.y);
297 sel.tclick2 = sel.tclick1;
305 xsetsel(getsel(), t);
309 propnotify(XEvent *e)
311 XPropertyEvent *xpev;
312 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
314 xpev = &e->xproperty;
315 if (xpev->state == PropertyNewValue &&
316 (xpev->atom == XA_PRIMARY ||
317 xpev->atom == clipboard)) {
325 ulong nitems, ofs, rem;
327 uchar *data, *last, *repl;
328 Atom type, incratom, property;
330 incratom = XInternAtom(xw.dpy, "INCR", 0);
333 if (e->type == SelectionNotify) {
334 property = e->xselection.property;
335 } else if(e->type == PropertyNotify) {
336 property = e->xproperty.atom;
340 if (property == None)
344 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
345 BUFSIZ/4, False, AnyPropertyType,
346 &type, &format, &nitems, &rem,
348 fprintf(stderr, "Clipboard allocation failed\n");
352 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
354 * If there is some PropertyNotify with no data, then
355 * this is the signal of the selection owner that all
356 * data has been transferred. We won't need to receive
357 * PropertyNotify events anymore.
359 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
360 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
364 if (type == incratom) {
366 * Activate the PropertyNotify events so we receive
367 * when the selection owner does send us the next
370 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
371 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
375 * Deleting the property is the transfer start signal.
377 XDeleteProperty(xw.dpy, xw.win, (int)property);
383 * Line endings are inconsistent in the terminal and GUI world
384 * copy and pasting. When receiving some selection data,
385 * replace all '\n' with '\r'.
386 * FIXME: Fix the computer world.
389 last = data + nitems * format / 8;
390 while ((repl = memchr(repl, '\n', last - repl))) {
394 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
395 ttywrite("\033[200~", 6);
396 ttysend((char *)data, nitems * format / 8);
397 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
398 ttywrite("\033[201~", 6);
400 /* number of 32-bit chunks returned */
401 ofs += nitems * format / 32;
405 * Deleting the property again tells the selection owner to send the
406 * next data chunk in the property.
408 XDeleteProperty(xw.dpy, xw.win, (int)property);
414 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
415 xw.win, CurrentTime);
423 if (sel.clipboard != NULL)
426 if (sel.primary != NULL) {
427 sel.clipboard = xstrdup(sel.primary);
428 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
429 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
438 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
439 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
440 xw.win, CurrentTime);
450 selrequest(XEvent *e)
452 XSelectionRequestEvent *xsre;
454 Atom xa_targets, string, clipboard;
457 xsre = (XSelectionRequestEvent *) e;
458 xev.type = SelectionNotify;
459 xev.requestor = xsre->requestor;
460 xev.selection = xsre->selection;
461 xev.target = xsre->target;
462 xev.time = xsre->time;
463 if (xsre->property == None)
464 xsre->property = xsre->target;
469 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
470 if (xsre->target == xa_targets) {
471 /* respond with the supported type */
472 string = xsel.xtarget;
473 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
474 XA_ATOM, 32, PropModeReplace,
475 (uchar *) &string, 1);
476 xev.property = xsre->property;
477 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
479 * xith XA_STRING non ascii characters may be incorrect in the
480 * requestor. It is not our problem, use utf8.
482 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
483 if (xsre->selection == XA_PRIMARY) {
484 seltext = sel.primary;
485 } else if (xsre->selection == clipboard) {
486 seltext = sel.clipboard;
489 "Unhandled clipboard selection 0x%lx\n",
493 if (seltext != NULL) {
494 XChangeProperty(xsre->display, xsre->requestor,
495 xsre->property, xsre->target,
497 (uchar *)seltext, strlen(seltext));
498 xev.property = xsre->property;
502 /* all done, send a notification to the listener */
503 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
504 fprintf(stderr, "Error sending SelectionNotify event\n");
508 xsetsel(char *str, Time t)
513 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
514 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
521 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
526 if (e->xbutton.button == Button2) {
528 } else if (e->xbutton.button == Button1) {
529 if (sel.mode == SEL_READY) {
531 selcopy(e->xbutton.time);
535 tsetdirt(sel.nb.y, sel.ne.y);
542 int oldey, oldex, oldsby, oldsey;
544 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
552 sel.mode = SEL_READY;
559 if (oldey != sel.oe.y || oldex != sel.oe.x)
560 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
564 xresize(int col, int row)
566 win.tw = MAX(1, col * win.cw);
567 win.th = MAX(1, row * win.ch);
569 XFreePixmap(xw.dpy, xw.buf);
570 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
571 DefaultDepth(xw.dpy, xw.scr));
572 XftDrawChange(xw.draw, xw.buf);
573 xclear(0, 0, win.w, win.h);
579 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
583 xloadcolor(int i, const char *name, Color *ncolor)
585 XRenderColor color = { .alpha = 0xffff };
588 if (BETWEEN(i, 16, 255)) { /* 256 color */
589 if (i < 6*6*6+16) { /* same colors as xterm */
590 color.red = sixd_to_16bit( ((i-16)/36)%6 );
591 color.green = sixd_to_16bit( ((i-16)/6) %6 );
592 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
593 } else { /* greyscale */
594 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
595 color.green = color.blue = color.red;
597 return XftColorAllocValue(xw.dpy, xw.vis,
598 xw.cmap, &color, ncolor);
603 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
613 dc.collen = MAX(colornamelen, 256);
614 dc.col = xmalloc(dc.collen * sizeof(Color));
617 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
618 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
621 for (i = 0; i < dc.collen; i++)
622 if (!xloadcolor(i, NULL, &dc.col[i])) {
624 die("Could not allocate color '%s'\n", colorname[i]);
626 die("Could not allocate color %d\n", i);
632 xsetcolorname(int x, const char *name)
636 if (!BETWEEN(x, 0, dc.collen))
640 if (!xloadcolor(x, name, &ncolor))
643 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
650 * Absolute coordinates.
653 xclear(int x1, int y1, int x2, int y2)
656 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
657 x1, y1, x2-x1, y2-y1);
663 XClassHint class = {opt_name ? opt_name : termname,
664 opt_class ? opt_class : termname};
665 XWMHints wm = {.flags = InputHint, .input = 1};
666 XSizeHints *sizeh = NULL;
668 sizeh = XAllocSizeHints();
670 sizeh->flags = PSize | PResizeInc | PBaseSize;
671 sizeh->height = win.h;
672 sizeh->width = win.w;
673 sizeh->height_inc = win.ch;
674 sizeh->width_inc = win.cw;
675 sizeh->base_height = 2 * borderpx;
676 sizeh->base_width = 2 * borderpx;
678 sizeh->flags |= PMaxSize | PMinSize;
679 sizeh->min_width = sizeh->max_width = win.w;
680 sizeh->min_height = sizeh->max_height = win.h;
682 if (xw.gm & (XValue|YValue)) {
683 sizeh->flags |= USPosition | PWinGravity;
686 sizeh->win_gravity = xgeommasktogravity(xw.gm);
689 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
695 xgeommasktogravity(int mask)
697 switch (mask & (XNegative|YNegative)) {
699 return NorthWestGravity;
701 return NorthEastGravity;
703 return SouthWestGravity;
706 return SouthEastGravity;
710 xloadfont(Font *f, FcPattern *pattern)
712 FcPattern *configured;
716 int wantattr, haveattr;
719 * Manually configure instead of calling XftMatchFont
720 * so that we can use the configured pattern for
721 * "missing glyph" lookups.
723 configured = FcPatternDuplicate(pattern);
727 FcConfigSubstitute(NULL, configured, FcMatchPattern);
728 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
730 match = FcFontMatch(NULL, configured, &result);
732 FcPatternDestroy(configured);
736 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
737 FcPatternDestroy(configured);
738 FcPatternDestroy(match);
742 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
745 * Check if xft was unable to find a font with the appropriate
746 * slant but gave us one anyway. Try to mitigate.
748 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
749 &haveattr) != XftResultMatch) || haveattr < wantattr) {
751 fputs("st: font slant does not match\n", stderr);
755 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
757 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
758 &haveattr) != XftResultMatch) || haveattr != wantattr) {
760 fputs("st: font weight does not match\n", stderr);
764 XftTextExtentsUtf8(xw.dpy, f->match,
765 (const FcChar8 *) ascii_printable,
766 strlen(ascii_printable), &extents);
769 f->pattern = configured;
771 f->ascent = f->match->ascent;
772 f->descent = f->match->descent;
774 f->rbearing = f->match->max_advance_width;
776 f->height = f->ascent + f->descent;
777 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
783 xloadfonts(char *fontstr, double fontsize)
789 if (fontstr[0] == '-') {
790 pattern = XftXlfdParse(fontstr, False, False);
792 pattern = FcNameParse((FcChar8 *)fontstr);
796 die("st: can't open font %s\n", fontstr);
799 FcPatternDel(pattern, FC_PIXEL_SIZE);
800 FcPatternDel(pattern, FC_SIZE);
801 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
802 usedfontsize = fontsize;
804 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
806 usedfontsize = fontval;
807 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
812 * Default font size is 12, if none given. This is to
813 * have a known usedfontsize value.
815 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
818 defaultfontsize = usedfontsize;
821 if (xloadfont(&dc.font, pattern))
822 die("st: can't open font %s\n", fontstr);
824 if (usedfontsize < 0) {
825 FcPatternGetDouble(dc.font.match->pattern,
826 FC_PIXEL_SIZE, 0, &fontval);
827 usedfontsize = fontval;
829 defaultfontsize = fontval;
832 /* Setting character width and height. */
833 win.cw = ceilf(dc.font.width * cwscale);
834 win.ch = ceilf(dc.font.height * chscale);
836 FcPatternDel(pattern, FC_SLANT);
837 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
838 if (xloadfont(&dc.ifont, pattern))
839 die("st: can't open font %s\n", fontstr);
841 FcPatternDel(pattern, FC_WEIGHT);
842 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
843 if (xloadfont(&dc.ibfont, pattern))
844 die("st: can't open font %s\n", fontstr);
846 FcPatternDel(pattern, FC_SLANT);
847 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
848 if (xloadfont(&dc.bfont, pattern))
849 die("st: can't open font %s\n", fontstr);
851 FcPatternDestroy(pattern);
857 XftFontClose(xw.dpy, f->match);
858 FcPatternDestroy(f->pattern);
860 FcFontSetDestroy(f->set);
866 /* Free the loaded fonts in the font cache. */
868 XftFontClose(xw.dpy, frc[--frclen].font);
870 xunloadfont(&dc.font);
871 xunloadfont(&dc.bfont);
872 xunloadfont(&dc.ifont);
873 xunloadfont(&dc.ibfont);
882 pid_t thispid = getpid();
883 XColor xmousefg, xmousebg;
885 if (!(xw.dpy = XOpenDisplay(NULL)))
886 die("Can't open display\n");
887 xw.scr = XDefaultScreen(xw.dpy);
888 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
892 die("Could not init fontconfig.\n");
894 usedfont = (opt_font == NULL)? font : opt_font;
895 xloadfonts(usedfont, 0);
898 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
901 /* adjust fixed window geometry */
902 win.w = 2 * borderpx + term.col * win.cw;
903 win.h = 2 * borderpx + term.row * win.ch;
904 if (xw.gm & XNegative)
905 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
906 if (xw.gm & YNegative)
907 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
910 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
911 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
912 xw.attrs.bit_gravity = NorthWestGravity;
913 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
914 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
915 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
916 xw.attrs.colormap = xw.cmap;
918 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
919 parent = XRootWindow(xw.dpy, xw.scr);
920 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
921 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
922 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
923 | CWEventMask | CWColormap, &xw.attrs);
925 memset(&gcvalues, 0, sizeof(gcvalues));
926 gcvalues.graphics_exposures = False;
927 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
929 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
930 DefaultDepth(xw.dpy, xw.scr));
931 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
932 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
934 /* Xft rendering context */
935 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
938 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
939 XSetLocaleModifiers("@im=local");
940 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
941 XSetLocaleModifiers("@im=");
942 if ((xw.xim = XOpenIM(xw.dpy,
943 NULL, NULL, NULL)) == NULL) {
944 die("XOpenIM failed. Could not open input"
949 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
950 | XIMStatusNothing, XNClientWindow, xw.win,
951 XNFocusWindow, xw.win, NULL);
953 die("XCreateIC failed. Could not obtain input method.\n");
955 /* white cursor, black outline */
956 cursor = XCreateFontCursor(xw.dpy, mouseshape);
957 XDefineCursor(xw.dpy, xw.win, cursor);
959 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
960 xmousefg.red = 0xffff;
961 xmousefg.green = 0xffff;
962 xmousefg.blue = 0xffff;
965 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
966 xmousebg.red = 0x0000;
967 xmousebg.green = 0x0000;
968 xmousebg.blue = 0x0000;
971 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
973 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
974 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
975 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
976 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
978 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
979 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
980 PropModeReplace, (uchar *)&thispid, 1);
983 XMapWindow(xw.dpy, xw.win);
985 XSync(xw.dpy, False);
987 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
988 if (xsel.xtarget == None)
989 xsel.xtarget = XA_STRING;
993 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
995 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
996 ushort mode, prevmode = USHRT_MAX;
997 Font *font = &dc.font;
998 int frcflags = FRC_NORMAL;
999 float runewidth = win.cw;
1003 FcPattern *fcpattern, *fontpattern;
1004 FcFontSet *fcsets[] = { NULL };
1005 FcCharSet *fccharset;
1006 int i, f, numspecs = 0;
1008 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1009 /* Fetch rune and mode for current glyph. */
1011 mode = glyphs[i].mode;
1013 /* Skip dummy wide-character spacing. */
1014 if (mode == ATTR_WDUMMY)
1017 /* Determine font for glyph if different from previous glyph. */
1018 if (prevmode != mode) {
1021 frcflags = FRC_NORMAL;
1022 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1023 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1025 frcflags = FRC_ITALICBOLD;
1026 } else if (mode & ATTR_ITALIC) {
1028 frcflags = FRC_ITALIC;
1029 } else if (mode & ATTR_BOLD) {
1031 frcflags = FRC_BOLD;
1033 yp = winy + font->ascent;
1036 /* Lookup character index with default font. */
1037 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1039 specs[numspecs].font = font->match;
1040 specs[numspecs].glyph = glyphidx;
1041 specs[numspecs].x = (short)xp;
1042 specs[numspecs].y = (short)yp;
1048 /* Fallback on font cache, search the font cache for match. */
1049 for (f = 0; f < frclen; f++) {
1050 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1051 /* Everything correct. */
1052 if (glyphidx && frc[f].flags == frcflags)
1054 /* We got a default font for a not found glyph. */
1055 if (!glyphidx && frc[f].flags == frcflags
1056 && frc[f].unicodep == rune) {
1061 /* Nothing was found. Use fontconfig to find matching font. */
1064 font->set = FcFontSort(0, font->pattern,
1066 fcsets[0] = font->set;
1069 * Nothing was found in the cache. Now use
1070 * some dozen of Fontconfig calls to get the
1071 * font for one single character.
1073 * Xft and fontconfig are design failures.
1075 fcpattern = FcPatternDuplicate(font->pattern);
1076 fccharset = FcCharSetCreate();
1078 FcCharSetAddChar(fccharset, rune);
1079 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1081 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1083 FcConfigSubstitute(0, fcpattern,
1085 FcDefaultSubstitute(fcpattern);
1087 fontpattern = FcFontSetMatch(0, fcsets, 1,
1091 * Overwrite or create the new cache entry.
1093 if (frclen >= LEN(frc)) {
1094 frclen = LEN(frc) - 1;
1095 XftFontClose(xw.dpy, frc[frclen].font);
1096 frc[frclen].unicodep = 0;
1099 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1101 if (!frc[frclen].font)
1102 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1104 frc[frclen].flags = frcflags;
1105 frc[frclen].unicodep = rune;
1107 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1112 FcPatternDestroy(fcpattern);
1113 FcCharSetDestroy(fccharset);
1116 specs[numspecs].font = frc[f].font;
1117 specs[numspecs].glyph = glyphidx;
1118 specs[numspecs].x = (short)xp;
1119 specs[numspecs].y = (short)yp;
1128 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1130 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1131 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1132 width = charlen * win.cw;
1133 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1134 XRenderColor colfg, colbg;
1137 /* Fallback on color display for attributes not supported by the font */
1138 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1139 if (dc.ibfont.badslant || dc.ibfont.badweight)
1140 base.fg = defaultattr;
1141 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1142 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1143 base.fg = defaultattr;
1146 if (IS_TRUECOL(base.fg)) {
1147 colfg.alpha = 0xffff;
1148 colfg.red = TRUERED(base.fg);
1149 colfg.green = TRUEGREEN(base.fg);
1150 colfg.blue = TRUEBLUE(base.fg);
1151 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1154 fg = &dc.col[base.fg];
1157 if (IS_TRUECOL(base.bg)) {
1158 colbg.alpha = 0xffff;
1159 colbg.green = TRUEGREEN(base.bg);
1160 colbg.red = TRUERED(base.bg);
1161 colbg.blue = TRUEBLUE(base.bg);
1162 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1165 bg = &dc.col[base.bg];
1168 /* Change basic system colors [0-7] to bright system colors [8-15] */
1169 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1170 fg = &dc.col[base.fg + 8];
1172 if (IS_SET(MODE_REVERSE)) {
1173 if (fg == &dc.col[defaultfg]) {
1174 fg = &dc.col[defaultbg];
1176 colfg.red = ~fg->color.red;
1177 colfg.green = ~fg->color.green;
1178 colfg.blue = ~fg->color.blue;
1179 colfg.alpha = fg->color.alpha;
1180 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1185 if (bg == &dc.col[defaultbg]) {
1186 bg = &dc.col[defaultfg];
1188 colbg.red = ~bg->color.red;
1189 colbg.green = ~bg->color.green;
1190 colbg.blue = ~bg->color.blue;
1191 colbg.alpha = bg->color.alpha;
1192 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1198 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1199 colfg.red = fg->color.red / 2;
1200 colfg.green = fg->color.green / 2;
1201 colfg.blue = fg->color.blue / 2;
1202 colfg.alpha = fg->color.alpha;
1203 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1208 if (base.mode & ATTR_REVERSE) {
1214 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1217 if (base.mode & ATTR_INVISIBLE)
1220 /* Intelligent cleaning up of the borders. */
1222 xclear(0, (y == 0)? 0 : winy, borderpx,
1223 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1225 if (x + charlen >= term.col) {
1226 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1227 ((y >= term.row-1)? win.h : (winy + win.ch)));
1230 xclear(winx, 0, winx + width, borderpx);
1231 if (y == term.row-1)
1232 xclear(winx, winy + win.ch, winx + width, win.h);
1234 /* Clean up the region we want to draw to. */
1235 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1237 /* Set the clip region because Xft is sometimes dirty. */
1242 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1244 /* Render the glyphs. */
1245 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1247 /* Render underline and strikethrough. */
1248 if (base.mode & ATTR_UNDERLINE) {
1249 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1253 if (base.mode & ATTR_STRUCK) {
1254 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1258 /* Reset clip to none. */
1259 XftDrawSetClip(xw.draw, 0);
1263 xdrawglyph(Glyph g, int x, int y)
1266 XftGlyphFontSpec spec;
1268 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1269 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1275 static int oldx = 0, oldy = 0;
1277 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1278 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1281 LIMIT(oldx, 0, term.col-1);
1282 LIMIT(oldy, 0, term.row-1);
1286 /* adjust position if in dummy */
1287 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1289 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1292 /* remove the old cursor */
1293 og = term.line[oldy][oldx];
1294 if (ena_sel && selected(oldx, oldy))
1295 og.mode ^= ATTR_REVERSE;
1296 xdrawglyph(og, oldx, oldy);
1298 g.u = term.line[term.c.y][term.c.x].u;
1299 g.mode |= term.line[term.c.y][term.c.x].mode &
1300 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1303 * Select the right color for the right mode.
1305 if (IS_SET(MODE_REVERSE)) {
1306 g.mode |= ATTR_REVERSE;
1308 if (ena_sel && selected(term.c.x, term.c.y)) {
1309 drawcol = dc.col[defaultcs];
1312 drawcol = dc.col[defaultrcs];
1316 if (ena_sel && selected(term.c.x, term.c.y)) {
1317 drawcol = dc.col[defaultrcs];
1321 drawcol = dc.col[defaultcs];
1325 if (IS_SET(MODE_HIDE))
1328 /* draw the new one */
1329 if (win.state & WIN_FOCUSED) {
1330 switch (win.cursor) {
1331 case 7: /* st extension: snowman */
1332 utf8decode("☃", &g.u, UTF_SIZ);
1333 case 0: /* Blinking Block */
1334 case 1: /* Blinking Block (Default) */
1335 case 2: /* Steady Block */
1336 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1337 xdrawglyph(g, term.c.x, term.c.y);
1339 case 3: /* Blinking Underline */
1340 case 4: /* Steady Underline */
1341 XftDrawRect(xw.draw, &drawcol,
1342 borderpx + curx * win.cw,
1343 borderpx + (term.c.y + 1) * win.ch - \
1345 win.cw, cursorthickness);
1347 case 5: /* Blinking bar */
1348 case 6: /* Steady bar */
1349 XftDrawRect(xw.draw, &drawcol,
1350 borderpx + curx * win.cw,
1351 borderpx + term.c.y * win.ch,
1352 cursorthickness, win.ch);
1356 XftDrawRect(xw.draw, &drawcol,
1357 borderpx + curx * win.cw,
1358 borderpx + term.c.y * win.ch,
1360 XftDrawRect(xw.draw, &drawcol,
1361 borderpx + curx * win.cw,
1362 borderpx + term.c.y * win.ch,
1364 XftDrawRect(xw.draw, &drawcol,
1365 borderpx + (curx + 1) * win.cw - 1,
1366 borderpx + term.c.y * win.ch,
1368 XftDrawRect(xw.draw, &drawcol,
1369 borderpx + curx * win.cw,
1370 borderpx + (term.c.y + 1) * win.ch - 1,
1373 oldx = curx, oldy = term.c.y;
1379 char buf[sizeof(long) * 8 + 1];
1381 snprintf(buf, sizeof(buf), "%lu", xw.win);
1382 setenv("WINDOWID", buf, 1);
1390 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1392 XSetWMName(xw.dpy, xw.win, &prop);
1393 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1400 drawregion(0, 0, term.col, term.row);
1401 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1403 XSetForeground(xw.dpy, dc.gc,
1404 dc.col[IS_SET(MODE_REVERSE)?
1405 defaultfg : defaultbg].pixel);
1409 drawregion(int x1, int y1, int x2, int y2)
1411 int i, x, y, ox, numspecs;
1413 XftGlyphFontSpec *specs;
1414 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1416 if (!(win.state & WIN_VISIBLE))
1419 for (y = y1; y < y2; y++) {
1425 specs = term.specbuf;
1426 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1429 for (x = x1; x < x2 && i < numspecs; x++) {
1430 new = term.line[y][x];
1431 if (new.mode == ATTR_WDUMMY)
1433 if (ena_sel && selected(x, y))
1434 new.mode ^= ATTR_REVERSE;
1435 if (i > 0 && ATTRCMP(base, new)) {
1436 xdrawglyphfontspecs(specs, base, i, ox, y);
1448 xdrawglyphfontspecs(specs, base, i, ox, y);
1460 visibility(XEvent *ev)
1462 XVisibilityEvent *e = &ev->xvisibility;
1464 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1470 win.state &= ~WIN_VISIBLE;
1474 xsetpointermotion(int set)
1476 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1477 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1481 xseturgency(int add)
1483 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1485 MODBIT(h->flags, add, XUrgencyHint);
1486 XSetWMHints(xw.dpy, xw.win, h);
1493 XkbBell(xw.dpy, xw.win, vol, (Atom)NULL);
1499 XFocusChangeEvent *e = &ev->xfocus;
1501 if (e->mode == NotifyGrab)
1504 if (ev->type == FocusIn) {
1505 XSetICFocus(xw.xic);
1506 win.state |= WIN_FOCUSED;
1508 if (IS_SET(MODE_FOCUS))
1509 ttywrite("\033[I", 3);
1511 XUnsetICFocus(xw.xic);
1512 win.state &= ~WIN_FOCUSED;
1513 if (IS_SET(MODE_FOCUS))
1514 ttywrite("\033[O", 3);
1521 XKeyEvent *e = &ev->xkey;
1523 char buf[32], *customkey;
1529 if (IS_SET(MODE_KBDLOCK))
1532 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1534 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1535 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1536 bp->func(&(bp->arg));
1541 /* 2. custom keys from config.h */
1542 if ((customkey = kmap(ksym, e->state))) {
1543 ttysend(customkey, strlen(customkey));
1547 /* 3. composed string from input method */
1550 if (len == 1 && e->state & Mod1Mask) {
1551 if (IS_SET(MODE_8BIT)) {
1554 len = utf8encode(c, buf);
1571 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1573 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1574 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1575 win.state |= WIN_FOCUSED;
1577 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1578 win.state &= ~WIN_FOCUSED;
1580 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1581 /* Send SIGHUP to shell */
1590 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1593 cresize(e->xconfigure.width, e->xconfigure.height);
1601 int w = win.w, h = win.h;
1603 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1604 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1607 /* Waiting for window mapping */
1609 XNextEvent(xw.dpy, &ev);
1611 * This XFilterEvent call is required because of XOpenIM. It
1612 * does filter out the key event and some client message for
1613 * the input method too.
1615 if (XFilterEvent(&ev, None))
1617 if (ev.type == ConfigureNotify) {
1618 w = ev.xconfigure.width;
1619 h = ev.xconfigure.height;
1621 } while (ev.type != MapNotify);
1627 clock_gettime(CLOCK_MONOTONIC, &last);
1630 for (xev = actionfps;;) {
1632 FD_SET(cmdfd, &rfd);
1635 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1638 die("select failed: %s\n", strerror(errno));
1640 if (FD_ISSET(cmdfd, &rfd)) {
1643 blinkset = tattrset(ATTR_BLINK);
1645 MODBIT(term.mode, 0, MODE_BLINK);
1649 if (FD_ISSET(xfd, &rfd))
1652 clock_gettime(CLOCK_MONOTONIC, &now);
1653 drawtimeout.tv_sec = 0;
1654 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1658 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1659 tsetdirtattr(ATTR_BLINK);
1660 term.mode ^= MODE_BLINK;
1664 deltatime = TIMEDIFF(now, last);
1665 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1671 while (XPending(xw.dpy)) {
1672 XNextEvent(xw.dpy, &ev);
1673 if (XFilterEvent(&ev, None))
1675 if (handler[ev.type])
1676 (handler[ev.type])(&ev);
1682 if (xev && !FD_ISSET(xfd, &rfd))
1684 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1686 if (TIMEDIFF(now, lastblink) \
1688 drawtimeout.tv_nsec = 1000;
1690 drawtimeout.tv_nsec = (1E6 * \
1695 drawtimeout.tv_sec = \
1696 drawtimeout.tv_nsec / 1E9;
1697 drawtimeout.tv_nsec %= (long)1E9;
1709 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1710 " [-n name] [-o file]\n"
1711 " [-T title] [-t title] [-w windowid]"
1712 " [[-e] command [args ...]]\n"
1713 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1714 " [-n name] [-o file]\n"
1715 " [-T title] [-t title] [-w windowid] -l line"
1716 " [stty_args ...]\n", argv0, argv0);
1720 main(int argc, char *argv[])
1724 win.cursor = cursorshape;
1731 opt_class = EARGF(usage());
1738 opt_font = EARGF(usage());
1741 xw.gm = XParseGeometry(EARGF(usage()),
1742 &xw.l, &xw.t, &cols, &rows);
1748 opt_io = EARGF(usage());
1751 opt_line = EARGF(usage());
1754 opt_name = EARGF(usage());
1758 opt_title = EARGF(usage());
1761 opt_embed = EARGF(usage());
1764 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1772 /* eat all remaining arguments */
1774 if (!opt_title && !opt_line)
1775 opt_title = basename(xstrdup(argv[0]));
1777 setlocale(LC_CTYPE, "");
1778 XSetLocaleModifiers("");
1779 tnew(MAX(cols, 1), MAX(rows, 1));