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>
27 #define XEMBED_FOCUS_IN 4
28 #define XEMBED_FOCUS_OUT 5
31 #define TRUERED(x) (((x) & 0xff0000) >> 8)
32 #define TRUEGREEN(x) (((x) & 0xff00))
33 #define TRUEBLUE(x) (((x) & 0xff) << 8)
35 typedef XftDraw *Draw;
36 typedef XftColor Color;
38 /* Purely graphic info */
44 Atom xembed, wmdeletewin, netwmname, netwmpid;
49 XSetWindowAttributes attrs;
51 int isfixed; /* is fixed geometry? */
52 int l, t; /* left and top offset */
53 int gm; /* geometry mask */
79 Font font, bfont, ifont, ibfont;
83 static inline ushort sixd_to_16bit(int);
84 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
85 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
86 static void xdrawglyph(Glyph, int, int);
87 static void xclear(int, int, int, int);
88 static void xdrawcursor(void);
89 static int xgeommasktogravity(int);
90 static int xloadfont(Font *, FcPattern *);
91 static void xunloadfont(Font *);
92 static void xsetenv(void);
94 static void expose(XEvent *);
95 static void visibility(XEvent *);
96 static void unmap(XEvent *);
97 static void kpress(XEvent *);
98 static void cmessage(XEvent *);
99 static void resize(XEvent *);
100 static void focus(XEvent *);
101 static void brelease(XEvent *);
102 static void bpress(XEvent *);
103 static void bmotion(XEvent *);
104 static void propnotify(XEvent *);
105 static void selnotify(XEvent *);
106 static void selclear_(XEvent *);
107 static void selrequest(XEvent *);
109 static void selcopy(Time);
110 static void getbuttoninfo(XEvent *);
111 static void mousereport(XEvent *);
113 static void (*handler[LASTEvent])(XEvent *) = {
115 [ClientMessage] = cmessage,
116 [ConfigureNotify] = resize,
117 [VisibilityNotify] = visibility,
118 [UnmapNotify] = unmap,
122 [MotionNotify] = bmotion,
123 [ButtonPress] = bpress,
124 [ButtonRelease] = brelease,
126 * Uncomment if you want the selection to disappear when you select something
127 * different in another window.
129 /* [SelectionClear] = selclear_, */
130 [SelectionNotify] = selnotify,
132 * PropertyNotify is only turned on when there is some INCR transfer happening
133 * for the selection retrieval.
135 [PropertyNotify] = propnotify,
136 [SelectionRequest] = selrequest,
142 static XSelection xsel;
144 /* Font Ring Cache */
158 /* Fontcache is an array now. A new font will be appended to the array. */
159 static Fontcache frc[16];
160 static int frclen = 0;
163 getbuttoninfo(XEvent *e)
166 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
168 sel.alt = IS_SET(MODE_ALTSCREEN);
170 sel.oe.x = x2col(e->xbutton.x);
171 sel.oe.y = y2row(e->xbutton.y);
174 sel.type = SEL_REGULAR;
175 for (type = 1; type < selmaskslen; ++type) {
176 if (match(selmasks[type], state)) {
184 mousereport(XEvent *e)
186 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
187 button = e->xbutton.button, state = e->xbutton.state,
193 if (e->xbutton.type == MotionNotify) {
194 if (x == ox && y == oy)
196 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
198 /* MOUSE_MOTION: no reporting if no button is pressed */
199 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
202 button = oldbutton + 32;
206 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
213 if (e->xbutton.type == ButtonPress) {
217 } else if (e->xbutton.type == ButtonRelease) {
219 /* MODE_MOUSEX10: no button release reporting */
220 if (IS_SET(MODE_MOUSEX10))
222 if (button == 64 || button == 65)
227 if (!IS_SET(MODE_MOUSEX10)) {
228 button += ((state & ShiftMask ) ? 4 : 0)
229 + ((state & Mod4Mask ) ? 8 : 0)
230 + ((state & ControlMask) ? 16 : 0);
233 if (IS_SET(MODE_MOUSESGR)) {
234 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
236 e->xbutton.type == ButtonRelease ? 'm' : 'M');
237 } else if (x < 223 && y < 223) {
238 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
239 32+button, 32+x+1, 32+y+1);
253 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
258 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
259 if (e->xbutton.button == ms->b
260 && match(ms->mask, e->xbutton.state)) {
261 ttysend(ms->s, strlen(ms->s));
266 if (e->xbutton.button == Button1) {
267 clock_gettime(CLOCK_MONOTONIC, &now);
269 /* Clear previous selection, logically and visually. */
271 sel.mode = SEL_EMPTY;
272 sel.type = SEL_REGULAR;
273 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
274 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
277 * If the user clicks below predefined timeouts specific
278 * snapping behaviour is exposed.
280 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
281 sel.snap = SNAP_LINE;
282 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
283 sel.snap = SNAP_WORD;
290 sel.mode = SEL_READY;
291 tsetdirt(sel.nb.y, sel.ne.y);
292 sel.tclick2 = sel.tclick1;
300 xsetsel(getsel(), t);
304 propnotify(XEvent *e)
306 XPropertyEvent *xpev;
307 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
309 xpev = &e->xproperty;
310 if (xpev->state == PropertyNewValue &&
311 (xpev->atom == XA_PRIMARY ||
312 xpev->atom == clipboard)) {
320 ulong nitems, ofs, rem;
322 uchar *data, *last, *repl;
323 Atom type, incratom, property;
325 incratom = XInternAtom(xw.dpy, "INCR", 0);
328 if (e->type == SelectionNotify) {
329 property = e->xselection.property;
330 } else if(e->type == PropertyNotify) {
331 property = e->xproperty.atom;
335 if (property == None)
339 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
340 BUFSIZ/4, False, AnyPropertyType,
341 &type, &format, &nitems, &rem,
343 fprintf(stderr, "Clipboard allocation failed\n");
347 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
349 * If there is some PropertyNotify with no data, then
350 * this is the signal of the selection owner that all
351 * data has been transferred. We won't need to receive
352 * PropertyNotify events anymore.
354 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
355 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
359 if (type == incratom) {
361 * Activate the PropertyNotify events so we receive
362 * when the selection owner does send us the next
365 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
366 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
370 * Deleting the property is the transfer start signal.
372 XDeleteProperty(xw.dpy, xw.win, (int)property);
378 * Line endings are inconsistent in the terminal and GUI world
379 * copy and pasting. When receiving some selection data,
380 * replace all '\n' with '\r'.
381 * FIXME: Fix the computer world.
384 last = data + nitems * format / 8;
385 while ((repl = memchr(repl, '\n', last - repl))) {
389 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
390 ttywrite("\033[200~", 6);
391 ttysend((char *)data, nitems * format / 8);
392 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
393 ttywrite("\033[201~", 6);
395 /* number of 32-bit chunks returned */
396 ofs += nitems * format / 32;
400 * Deleting the property again tells the selection owner to send the
401 * next data chunk in the property.
403 XDeleteProperty(xw.dpy, xw.win, (int)property);
409 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
410 xw.win, CurrentTime);
418 if (sel.clipboard != NULL)
421 if (sel.primary != NULL) {
422 sel.clipboard = xstrdup(sel.primary);
423 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
424 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
433 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
434 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
435 xw.win, CurrentTime);
445 selrequest(XEvent *e)
447 XSelectionRequestEvent *xsre;
449 Atom xa_targets, string, clipboard;
452 xsre = (XSelectionRequestEvent *) e;
453 xev.type = SelectionNotify;
454 xev.requestor = xsre->requestor;
455 xev.selection = xsre->selection;
456 xev.target = xsre->target;
457 xev.time = xsre->time;
458 if (xsre->property == None)
459 xsre->property = xsre->target;
464 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
465 if (xsre->target == xa_targets) {
466 /* respond with the supported type */
467 string = xsel.xtarget;
468 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
469 XA_ATOM, 32, PropModeReplace,
470 (uchar *) &string, 1);
471 xev.property = xsre->property;
472 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
474 * xith XA_STRING non ascii characters may be incorrect in the
475 * requestor. It is not our problem, use utf8.
477 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
478 if (xsre->selection == XA_PRIMARY) {
479 seltext = sel.primary;
480 } else if (xsre->selection == clipboard) {
481 seltext = sel.clipboard;
484 "Unhandled clipboard selection 0x%lx\n",
488 if (seltext != NULL) {
489 XChangeProperty(xsre->display, xsre->requestor,
490 xsre->property, xsre->target,
492 (uchar *)seltext, strlen(seltext));
493 xev.property = xsre->property;
497 /* all done, send a notification to the listener */
498 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
499 fprintf(stderr, "Error sending SelectionNotify event\n");
503 xsetsel(char *str, Time t)
508 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
509 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
516 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
521 if (e->xbutton.button == Button2) {
523 } else if (e->xbutton.button == Button1) {
524 if (sel.mode == SEL_READY) {
526 selcopy(e->xbutton.time);
530 tsetdirt(sel.nb.y, sel.ne.y);
537 int oldey, oldex, oldsby, oldsey;
539 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
547 sel.mode = SEL_READY;
554 if (oldey != sel.oe.y || oldex != sel.oe.x)
555 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
559 xresize(int col, int row)
561 win.tw = MAX(1, col * win.cw);
562 win.th = MAX(1, row * win.ch);
564 XFreePixmap(xw.dpy, xw.buf);
565 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
566 DefaultDepth(xw.dpy, xw.scr));
567 XftDrawChange(xw.draw, xw.buf);
568 xclear(0, 0, win.w, win.h);
574 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
578 xloadcolor(int i, const char *name, Color *ncolor)
580 XRenderColor color = { .alpha = 0xffff };
583 if (BETWEEN(i, 16, 255)) { /* 256 color */
584 if (i < 6*6*6+16) { /* same colors as xterm */
585 color.red = sixd_to_16bit( ((i-16)/36)%6 );
586 color.green = sixd_to_16bit( ((i-16)/6) %6 );
587 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
588 } else { /* greyscale */
589 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
590 color.green = color.blue = color.red;
592 return XftColorAllocValue(xw.dpy, xw.vis,
593 xw.cmap, &color, ncolor);
598 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
608 dc.collen = MAX(colornamelen, 256);
609 dc.col = xmalloc(dc.collen * sizeof(Color));
612 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
613 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
616 for (i = 0; i < dc.collen; i++)
617 if (!xloadcolor(i, NULL, &dc.col[i])) {
619 die("Could not allocate color '%s'\n", colorname[i]);
621 die("Could not allocate color %d\n", i);
627 xsetcolorname(int x, const char *name)
631 if (!BETWEEN(x, 0, dc.collen))
635 if (!xloadcolor(x, name, &ncolor))
638 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
645 * Absolute coordinates.
648 xclear(int x1, int y1, int x2, int y2)
651 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
652 x1, y1, x2-x1, y2-y1);
658 XClassHint class = {opt_name ? opt_name : termname,
659 opt_class ? opt_class : termname};
660 XWMHints wm = {.flags = InputHint, .input = 1};
661 XSizeHints *sizeh = NULL;
663 sizeh = XAllocSizeHints();
665 sizeh->flags = PSize | PResizeInc | PBaseSize;
666 sizeh->height = win.h;
667 sizeh->width = win.w;
668 sizeh->height_inc = win.ch;
669 sizeh->width_inc = win.cw;
670 sizeh->base_height = 2 * borderpx;
671 sizeh->base_width = 2 * borderpx;
673 sizeh->flags |= PMaxSize | PMinSize;
674 sizeh->min_width = sizeh->max_width = win.w;
675 sizeh->min_height = sizeh->max_height = win.h;
677 if (xw.gm & (XValue|YValue)) {
678 sizeh->flags |= USPosition | PWinGravity;
681 sizeh->win_gravity = xgeommasktogravity(xw.gm);
684 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
690 xgeommasktogravity(int mask)
692 switch (mask & (XNegative|YNegative)) {
694 return NorthWestGravity;
696 return NorthEastGravity;
698 return SouthWestGravity;
701 return SouthEastGravity;
705 xloadfont(Font *f, FcPattern *pattern)
707 FcPattern *configured;
711 int wantattr, haveattr;
714 * Manually configure instead of calling XftMatchFont
715 * so that we can use the configured pattern for
716 * "missing glyph" lookups.
718 configured = FcPatternDuplicate(pattern);
722 FcConfigSubstitute(NULL, configured, FcMatchPattern);
723 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
725 match = FcFontMatch(NULL, configured, &result);
727 FcPatternDestroy(configured);
731 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
732 FcPatternDestroy(configured);
733 FcPatternDestroy(match);
737 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
740 * Check if xft was unable to find a font with the appropriate
741 * slant but gave us one anyway. Try to mitigate.
743 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
744 &haveattr) != XftResultMatch) || haveattr < wantattr) {
746 fputs("st: font slant does not match\n", stderr);
750 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
752 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
753 &haveattr) != XftResultMatch) || haveattr != wantattr) {
755 fputs("st: font weight does not match\n", stderr);
759 XftTextExtentsUtf8(xw.dpy, f->match,
760 (const FcChar8 *) ascii_printable,
761 strlen(ascii_printable), &extents);
764 f->pattern = configured;
766 f->ascent = f->match->ascent;
767 f->descent = f->match->descent;
769 f->rbearing = f->match->max_advance_width;
771 f->height = f->ascent + f->descent;
772 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
778 xloadfonts(char *fontstr, double fontsize)
784 if (fontstr[0] == '-') {
785 pattern = XftXlfdParse(fontstr, False, False);
787 pattern = FcNameParse((FcChar8 *)fontstr);
791 die("st: can't open font %s\n", fontstr);
794 FcPatternDel(pattern, FC_PIXEL_SIZE);
795 FcPatternDel(pattern, FC_SIZE);
796 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
797 usedfontsize = fontsize;
799 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
801 usedfontsize = fontval;
802 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
807 * Default font size is 12, if none given. This is to
808 * have a known usedfontsize value.
810 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
813 defaultfontsize = usedfontsize;
816 if (xloadfont(&dc.font, pattern))
817 die("st: can't open font %s\n", fontstr);
819 if (usedfontsize < 0) {
820 FcPatternGetDouble(dc.font.match->pattern,
821 FC_PIXEL_SIZE, 0, &fontval);
822 usedfontsize = fontval;
824 defaultfontsize = fontval;
827 /* Setting character width and height. */
828 win.cw = ceilf(dc.font.width * cwscale);
829 win.ch = ceilf(dc.font.height * chscale);
831 FcPatternDel(pattern, FC_SLANT);
832 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
833 if (xloadfont(&dc.ifont, pattern))
834 die("st: can't open font %s\n", fontstr);
836 FcPatternDel(pattern, FC_WEIGHT);
837 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
838 if (xloadfont(&dc.ibfont, pattern))
839 die("st: can't open font %s\n", fontstr);
841 FcPatternDel(pattern, FC_SLANT);
842 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
843 if (xloadfont(&dc.bfont, pattern))
844 die("st: can't open font %s\n", fontstr);
846 FcPatternDestroy(pattern);
852 XftFontClose(xw.dpy, f->match);
853 FcPatternDestroy(f->pattern);
855 FcFontSetDestroy(f->set);
861 /* Free the loaded fonts in the font cache. */
863 XftFontClose(xw.dpy, frc[--frclen].font);
865 xunloadfont(&dc.font);
866 xunloadfont(&dc.bfont);
867 xunloadfont(&dc.ifont);
868 xunloadfont(&dc.ibfont);
877 pid_t thispid = getpid();
878 XColor xmousefg, xmousebg;
880 if (!(xw.dpy = XOpenDisplay(NULL)))
881 die("Can't open display\n");
882 xw.scr = XDefaultScreen(xw.dpy);
883 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
887 die("Could not init fontconfig.\n");
889 usedfont = (opt_font == NULL)? font : opt_font;
890 xloadfonts(usedfont, 0);
893 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
896 /* adjust fixed window geometry */
897 win.w = 2 * borderpx + term.col * win.cw;
898 win.h = 2 * borderpx + term.row * win.ch;
899 if (xw.gm & XNegative)
900 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
901 if (xw.gm & YNegative)
902 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
905 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
906 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
907 xw.attrs.bit_gravity = NorthWestGravity;
908 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
909 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
910 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
911 xw.attrs.colormap = xw.cmap;
913 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
914 parent = XRootWindow(xw.dpy, xw.scr);
915 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
916 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
917 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
918 | CWEventMask | CWColormap, &xw.attrs);
920 memset(&gcvalues, 0, sizeof(gcvalues));
921 gcvalues.graphics_exposures = False;
922 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
924 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
925 DefaultDepth(xw.dpy, xw.scr));
926 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
927 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
929 /* Xft rendering context */
930 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
933 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
934 XSetLocaleModifiers("@im=local");
935 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
936 XSetLocaleModifiers("@im=");
937 if ((xw.xim = XOpenIM(xw.dpy,
938 NULL, NULL, NULL)) == NULL) {
939 die("XOpenIM failed. Could not open input"
944 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
945 | XIMStatusNothing, XNClientWindow, xw.win,
946 XNFocusWindow, xw.win, NULL);
948 die("XCreateIC failed. Could not obtain input method.\n");
950 /* white cursor, black outline */
951 cursor = XCreateFontCursor(xw.dpy, mouseshape);
952 XDefineCursor(xw.dpy, xw.win, cursor);
954 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
955 xmousefg.red = 0xffff;
956 xmousefg.green = 0xffff;
957 xmousefg.blue = 0xffff;
960 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
961 xmousebg.red = 0x0000;
962 xmousebg.green = 0x0000;
963 xmousebg.blue = 0x0000;
966 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
968 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
969 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
970 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
971 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
973 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
974 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
975 PropModeReplace, (uchar *)&thispid, 1);
978 XMapWindow(xw.dpy, xw.win);
980 XSync(xw.dpy, False);
982 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
983 if (xsel.xtarget == None)
984 xsel.xtarget = XA_STRING;
988 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
990 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
991 ushort mode, prevmode = USHRT_MAX;
992 Font *font = &dc.font;
993 int frcflags = FRC_NORMAL;
994 float runewidth = win.cw;
998 FcPattern *fcpattern, *fontpattern;
999 FcFontSet *fcsets[] = { NULL };
1000 FcCharSet *fccharset;
1001 int i, f, numspecs = 0;
1003 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1004 /* Fetch rune and mode for current glyph. */
1006 mode = glyphs[i].mode;
1008 /* Skip dummy wide-character spacing. */
1009 if (mode == ATTR_WDUMMY)
1012 /* Determine font for glyph if different from previous glyph. */
1013 if (prevmode != mode) {
1016 frcflags = FRC_NORMAL;
1017 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1018 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1020 frcflags = FRC_ITALICBOLD;
1021 } else if (mode & ATTR_ITALIC) {
1023 frcflags = FRC_ITALIC;
1024 } else if (mode & ATTR_BOLD) {
1026 frcflags = FRC_BOLD;
1028 yp = winy + font->ascent;
1031 /* Lookup character index with default font. */
1032 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1034 specs[numspecs].font = font->match;
1035 specs[numspecs].glyph = glyphidx;
1036 specs[numspecs].x = (short)xp;
1037 specs[numspecs].y = (short)yp;
1043 /* Fallback on font cache, search the font cache for match. */
1044 for (f = 0; f < frclen; f++) {
1045 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1046 /* Everything correct. */
1047 if (glyphidx && frc[f].flags == frcflags)
1049 /* We got a default font for a not found glyph. */
1050 if (!glyphidx && frc[f].flags == frcflags
1051 && frc[f].unicodep == rune) {
1056 /* Nothing was found. Use fontconfig to find matching font. */
1059 font->set = FcFontSort(0, font->pattern,
1061 fcsets[0] = font->set;
1064 * Nothing was found in the cache. Now use
1065 * some dozen of Fontconfig calls to get the
1066 * font for one single character.
1068 * Xft and fontconfig are design failures.
1070 fcpattern = FcPatternDuplicate(font->pattern);
1071 fccharset = FcCharSetCreate();
1073 FcCharSetAddChar(fccharset, rune);
1074 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1076 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1078 FcConfigSubstitute(0, fcpattern,
1080 FcDefaultSubstitute(fcpattern);
1082 fontpattern = FcFontSetMatch(0, fcsets, 1,
1086 * Overwrite or create the new cache entry.
1088 if (frclen >= LEN(frc)) {
1089 frclen = LEN(frc) - 1;
1090 XftFontClose(xw.dpy, frc[frclen].font);
1091 frc[frclen].unicodep = 0;
1094 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1096 if (!frc[frclen].font)
1097 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1099 frc[frclen].flags = frcflags;
1100 frc[frclen].unicodep = rune;
1102 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1107 FcPatternDestroy(fcpattern);
1108 FcCharSetDestroy(fccharset);
1111 specs[numspecs].font = frc[f].font;
1112 specs[numspecs].glyph = glyphidx;
1113 specs[numspecs].x = (short)xp;
1114 specs[numspecs].y = (short)yp;
1123 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1125 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1126 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1127 width = charlen * win.cw;
1128 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1129 XRenderColor colfg, colbg;
1132 /* Fallback on color display for attributes not supported by the font */
1133 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1134 if (dc.ibfont.badslant || dc.ibfont.badweight)
1135 base.fg = defaultattr;
1136 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1137 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1138 base.fg = defaultattr;
1141 if (IS_TRUECOL(base.fg)) {
1142 colfg.alpha = 0xffff;
1143 colfg.red = TRUERED(base.fg);
1144 colfg.green = TRUEGREEN(base.fg);
1145 colfg.blue = TRUEBLUE(base.fg);
1146 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1149 fg = &dc.col[base.fg];
1152 if (IS_TRUECOL(base.bg)) {
1153 colbg.alpha = 0xffff;
1154 colbg.green = TRUEGREEN(base.bg);
1155 colbg.red = TRUERED(base.bg);
1156 colbg.blue = TRUEBLUE(base.bg);
1157 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1160 bg = &dc.col[base.bg];
1163 /* Change basic system colors [0-7] to bright system colors [8-15] */
1164 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1165 fg = &dc.col[base.fg + 8];
1167 if (IS_SET(MODE_REVERSE)) {
1168 if (fg == &dc.col[defaultfg]) {
1169 fg = &dc.col[defaultbg];
1171 colfg.red = ~fg->color.red;
1172 colfg.green = ~fg->color.green;
1173 colfg.blue = ~fg->color.blue;
1174 colfg.alpha = fg->color.alpha;
1175 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1180 if (bg == &dc.col[defaultbg]) {
1181 bg = &dc.col[defaultfg];
1183 colbg.red = ~bg->color.red;
1184 colbg.green = ~bg->color.green;
1185 colbg.blue = ~bg->color.blue;
1186 colbg.alpha = bg->color.alpha;
1187 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1193 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1194 colfg.red = fg->color.red / 2;
1195 colfg.green = fg->color.green / 2;
1196 colfg.blue = fg->color.blue / 2;
1197 colfg.alpha = fg->color.alpha;
1198 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1203 if (base.mode & ATTR_REVERSE) {
1209 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1212 if (base.mode & ATTR_INVISIBLE)
1215 /* Intelligent cleaning up of the borders. */
1217 xclear(0, (y == 0)? 0 : winy, borderpx,
1218 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1220 if (x + charlen >= term.col) {
1221 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1222 ((y >= term.row-1)? win.h : (winy + win.ch)));
1225 xclear(winx, 0, winx + width, borderpx);
1226 if (y == term.row-1)
1227 xclear(winx, winy + win.ch, winx + width, win.h);
1229 /* Clean up the region we want to draw to. */
1230 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1232 /* Set the clip region because Xft is sometimes dirty. */
1237 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1239 /* Render the glyphs. */
1240 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1242 /* Render underline and strikethrough. */
1243 if (base.mode & ATTR_UNDERLINE) {
1244 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1248 if (base.mode & ATTR_STRUCK) {
1249 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1253 /* Reset clip to none. */
1254 XftDrawSetClip(xw.draw, 0);
1258 xdrawglyph(Glyph g, int x, int y)
1261 XftGlyphFontSpec spec;
1263 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1264 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1270 static int oldx = 0, oldy = 0;
1272 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1273 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1276 LIMIT(oldx, 0, term.col-1);
1277 LIMIT(oldy, 0, term.row-1);
1281 /* adjust position if in dummy */
1282 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1284 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1287 /* remove the old cursor */
1288 og = term.line[oldy][oldx];
1289 if (ena_sel && selected(oldx, oldy))
1290 og.mode ^= ATTR_REVERSE;
1291 xdrawglyph(og, oldx, oldy);
1293 g.u = term.line[term.c.y][term.c.x].u;
1294 g.mode |= term.line[term.c.y][term.c.x].mode &
1295 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1298 * Select the right color for the right mode.
1300 if (IS_SET(MODE_REVERSE)) {
1301 g.mode |= ATTR_REVERSE;
1303 if (ena_sel && selected(term.c.x, term.c.y)) {
1304 drawcol = dc.col[defaultcs];
1307 drawcol = dc.col[defaultrcs];
1311 if (ena_sel && selected(term.c.x, term.c.y)) {
1312 drawcol = dc.col[defaultrcs];
1316 drawcol = dc.col[defaultcs];
1320 if (IS_SET(MODE_HIDE))
1323 /* draw the new one */
1324 if (win.state & WIN_FOCUSED) {
1325 switch (win.cursor) {
1326 case 7: /* st extension: snowman */
1327 utf8decode("☃", &g.u, UTF_SIZ);
1328 case 0: /* Blinking Block */
1329 case 1: /* Blinking Block (Default) */
1330 case 2: /* Steady Block */
1331 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1332 xdrawglyph(g, term.c.x, term.c.y);
1334 case 3: /* Blinking Underline */
1335 case 4: /* Steady Underline */
1336 XftDrawRect(xw.draw, &drawcol,
1337 borderpx + curx * win.cw,
1338 borderpx + (term.c.y + 1) * win.ch - \
1340 win.cw, cursorthickness);
1342 case 5: /* Blinking bar */
1343 case 6: /* Steady bar */
1344 XftDrawRect(xw.draw, &drawcol,
1345 borderpx + curx * win.cw,
1346 borderpx + term.c.y * win.ch,
1347 cursorthickness, win.ch);
1351 XftDrawRect(xw.draw, &drawcol,
1352 borderpx + curx * win.cw,
1353 borderpx + term.c.y * win.ch,
1355 XftDrawRect(xw.draw, &drawcol,
1356 borderpx + curx * win.cw,
1357 borderpx + term.c.y * win.ch,
1359 XftDrawRect(xw.draw, &drawcol,
1360 borderpx + (curx + 1) * win.cw - 1,
1361 borderpx + term.c.y * win.ch,
1363 XftDrawRect(xw.draw, &drawcol,
1364 borderpx + curx * win.cw,
1365 borderpx + (term.c.y + 1) * win.ch - 1,
1368 oldx = curx, oldy = term.c.y;
1374 char buf[sizeof(long) * 8 + 1];
1376 snprintf(buf, sizeof(buf), "%lu", xw.win);
1377 setenv("WINDOWID", buf, 1);
1385 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1387 XSetWMName(xw.dpy, xw.win, &prop);
1388 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1395 drawregion(0, 0, term.col, term.row);
1396 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1398 XSetForeground(xw.dpy, dc.gc,
1399 dc.col[IS_SET(MODE_REVERSE)?
1400 defaultfg : defaultbg].pixel);
1404 drawregion(int x1, int y1, int x2, int y2)
1406 int i, x, y, ox, numspecs;
1408 XftGlyphFontSpec *specs;
1409 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1411 if (!(win.state & WIN_VISIBLE))
1414 for (y = y1; y < y2; y++) {
1420 specs = term.specbuf;
1421 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1424 for (x = x1; x < x2 && i < numspecs; x++) {
1425 new = term.line[y][x];
1426 if (new.mode == ATTR_WDUMMY)
1428 if (ena_sel && selected(x, y))
1429 new.mode ^= ATTR_REVERSE;
1430 if (i > 0 && ATTRCMP(base, new)) {
1431 xdrawglyphfontspecs(specs, base, i, ox, y);
1443 xdrawglyphfontspecs(specs, base, i, ox, y);
1455 visibility(XEvent *ev)
1457 XVisibilityEvent *e = &ev->xvisibility;
1459 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1465 win.state &= ~WIN_VISIBLE;
1469 xsetpointermotion(int set)
1471 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1472 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1476 xseturgency(int add)
1478 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1480 MODBIT(h->flags, add, XUrgencyHint);
1481 XSetWMHints(xw.dpy, xw.win, h);
1488 XkbBell(xw.dpy, xw.win, vol, (Atom)NULL);
1494 XFocusChangeEvent *e = &ev->xfocus;
1496 if (e->mode == NotifyGrab)
1499 if (ev->type == FocusIn) {
1500 XSetICFocus(xw.xic);
1501 win.state |= WIN_FOCUSED;
1503 if (IS_SET(MODE_FOCUS))
1504 ttywrite("\033[I", 3);
1506 XUnsetICFocus(xw.xic);
1507 win.state &= ~WIN_FOCUSED;
1508 if (IS_SET(MODE_FOCUS))
1509 ttywrite("\033[O", 3);
1516 XKeyEvent *e = &ev->xkey;
1518 char buf[32], *customkey;
1524 if (IS_SET(MODE_KBDLOCK))
1527 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1529 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1530 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1531 bp->func(&(bp->arg));
1536 /* 2. custom keys from config.h */
1537 if ((customkey = kmap(ksym, e->state))) {
1538 ttysend(customkey, strlen(customkey));
1542 /* 3. composed string from input method */
1545 if (len == 1 && e->state & Mod1Mask) {
1546 if (IS_SET(MODE_8BIT)) {
1549 len = utf8encode(c, buf);
1566 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1568 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1569 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1570 win.state |= WIN_FOCUSED;
1572 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1573 win.state &= ~WIN_FOCUSED;
1575 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1576 /* Send SIGHUP to shell */
1585 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1588 cresize(e->xconfigure.width, e->xconfigure.height);
1596 int w = win.w, h = win.h;
1598 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1599 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1602 /* Waiting for window mapping */
1604 XNextEvent(xw.dpy, &ev);
1606 * This XFilterEvent call is required because of XOpenIM. It
1607 * does filter out the key event and some client message for
1608 * the input method too.
1610 if (XFilterEvent(&ev, None))
1612 if (ev.type == ConfigureNotify) {
1613 w = ev.xconfigure.width;
1614 h = ev.xconfigure.height;
1616 } while (ev.type != MapNotify);
1622 clock_gettime(CLOCK_MONOTONIC, &last);
1625 for (xev = actionfps;;) {
1627 FD_SET(cmdfd, &rfd);
1630 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1633 die("select failed: %s\n", strerror(errno));
1635 if (FD_ISSET(cmdfd, &rfd)) {
1638 blinkset = tattrset(ATTR_BLINK);
1640 MODBIT(term.mode, 0, MODE_BLINK);
1644 if (FD_ISSET(xfd, &rfd))
1647 clock_gettime(CLOCK_MONOTONIC, &now);
1648 drawtimeout.tv_sec = 0;
1649 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1653 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1654 tsetdirtattr(ATTR_BLINK);
1655 term.mode ^= MODE_BLINK;
1659 deltatime = TIMEDIFF(now, last);
1660 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1666 while (XPending(xw.dpy)) {
1667 XNextEvent(xw.dpy, &ev);
1668 if (XFilterEvent(&ev, None))
1670 if (handler[ev.type])
1671 (handler[ev.type])(&ev);
1677 if (xev && !FD_ISSET(xfd, &rfd))
1679 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1681 if (TIMEDIFF(now, lastblink) \
1683 drawtimeout.tv_nsec = 1000;
1685 drawtimeout.tv_nsec = (1E6 * \
1690 drawtimeout.tv_sec = \
1691 drawtimeout.tv_nsec / 1E9;
1692 drawtimeout.tv_nsec %= (long)1E9;
1702 main(int argc, char *argv[])
1706 win.cursor = cursorshape;
1713 opt_class = EARGF(usage());
1720 opt_font = EARGF(usage());
1723 xw.gm = XParseGeometry(EARGF(usage()),
1724 &xw.l, &xw.t, &cols, &rows);
1730 opt_io = EARGF(usage());
1733 opt_line = EARGF(usage());
1736 opt_name = EARGF(usage());
1740 opt_title = EARGF(usage());
1743 opt_embed = EARGF(usage());
1746 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1754 /* eat all remaining arguments */
1756 if (!opt_title && !opt_line)
1757 opt_title = basename(xstrdup(argv[0]));
1759 setlocale(LC_CTYPE, "");
1760 XSetLocaleModifiers("");
1761 tnew(MAX(cols, 1), MAX(rows, 1));