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 *);
93 static void expose(XEvent *);
94 static void visibility(XEvent *);
95 static void unmap(XEvent *);
96 static void kpress(XEvent *);
97 static void cmessage(XEvent *);
98 static void resize(XEvent *);
99 static void focus(XEvent *);
100 static void brelease(XEvent *);
101 static void bpress(XEvent *);
102 static void bmotion(XEvent *);
103 static void propnotify(XEvent *);
104 static void selnotify(XEvent *);
105 static void selclear_(XEvent *);
106 static void selrequest(XEvent *);
108 static void selcopy(Time);
109 static void getbuttoninfo(XEvent *);
110 static void mousereport(XEvent *);
112 static void (*handler[LASTEvent])(XEvent *) = {
114 [ClientMessage] = cmessage,
115 [ConfigureNotify] = resize,
116 [VisibilityNotify] = visibility,
117 [UnmapNotify] = unmap,
121 [MotionNotify] = bmotion,
122 [ButtonPress] = bpress,
123 [ButtonRelease] = brelease,
125 * Uncomment if you want the selection to disappear when you select something
126 * different in another window.
128 /* [SelectionClear] = selclear_, */
129 [SelectionNotify] = selnotify,
131 * PropertyNotify is only turned on when there is some INCR transfer happening
132 * for the selection retrieval.
134 [PropertyNotify] = propnotify,
135 [SelectionRequest] = selrequest,
141 static XSelection xsel;
143 /* Font Ring Cache */
157 /* Fontcache is an array now. A new font will be appended to the array. */
158 static Fontcache frc[16];
159 static int frclen = 0;
162 getbuttoninfo(XEvent *e)
165 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
167 sel.alt = IS_SET(MODE_ALTSCREEN);
169 sel.oe.x = x2col(e->xbutton.x);
170 sel.oe.y = y2row(e->xbutton.y);
173 sel.type = SEL_REGULAR;
174 for (type = 1; type < selmaskslen; ++type) {
175 if (match(selmasks[type], state)) {
183 mousereport(XEvent *e)
185 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
186 button = e->xbutton.button, state = e->xbutton.state,
192 if (e->xbutton.type == MotionNotify) {
193 if (x == ox && y == oy)
195 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
197 /* MOUSE_MOTION: no reporting if no button is pressed */
198 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
201 button = oldbutton + 32;
205 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
212 if (e->xbutton.type == ButtonPress) {
216 } else if (e->xbutton.type == ButtonRelease) {
218 /* MODE_MOUSEX10: no button release reporting */
219 if (IS_SET(MODE_MOUSEX10))
221 if (button == 64 || button == 65)
226 if (!IS_SET(MODE_MOUSEX10)) {
227 button += ((state & ShiftMask ) ? 4 : 0)
228 + ((state & Mod4Mask ) ? 8 : 0)
229 + ((state & ControlMask) ? 16 : 0);
232 if (IS_SET(MODE_MOUSESGR)) {
233 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
235 e->xbutton.type == ButtonRelease ? 'm' : 'M');
236 } else if (x < 223 && y < 223) {
237 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
238 32+button, 32+x+1, 32+y+1);
252 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
257 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
258 if (e->xbutton.button == ms->b
259 && match(ms->mask, e->xbutton.state)) {
260 ttysend(ms->s, strlen(ms->s));
265 if (e->xbutton.button == Button1) {
266 clock_gettime(CLOCK_MONOTONIC, &now);
268 /* Clear previous selection, logically and visually. */
270 sel.mode = SEL_EMPTY;
271 sel.type = SEL_REGULAR;
272 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
273 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
276 * If the user clicks below predefined timeouts specific
277 * snapping behaviour is exposed.
279 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
280 sel.snap = SNAP_LINE;
281 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
282 sel.snap = SNAP_WORD;
289 sel.mode = SEL_READY;
290 tsetdirt(sel.nb.y, sel.ne.y);
291 sel.tclick2 = sel.tclick1;
299 xsetsel(getsel(), t);
303 propnotify(XEvent *e)
305 XPropertyEvent *xpev;
306 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
308 xpev = &e->xproperty;
309 if (xpev->state == PropertyNewValue &&
310 (xpev->atom == XA_PRIMARY ||
311 xpev->atom == clipboard)) {
319 ulong nitems, ofs, rem;
321 uchar *data, *last, *repl;
322 Atom type, incratom, property;
324 incratom = XInternAtom(xw.dpy, "INCR", 0);
327 if (e->type == SelectionNotify) {
328 property = e->xselection.property;
329 } else if(e->type == PropertyNotify) {
330 property = e->xproperty.atom;
334 if (property == None)
338 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
339 BUFSIZ/4, False, AnyPropertyType,
340 &type, &format, &nitems, &rem,
342 fprintf(stderr, "Clipboard allocation failed\n");
346 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
348 * If there is some PropertyNotify with no data, then
349 * this is the signal of the selection owner that all
350 * data has been transferred. We won't need to receive
351 * PropertyNotify events anymore.
353 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
354 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
358 if (type == incratom) {
360 * Activate the PropertyNotify events so we receive
361 * when the selection owner does send us the next
364 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
365 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
369 * Deleting the property is the transfer start signal.
371 XDeleteProperty(xw.dpy, xw.win, (int)property);
377 * Line endings are inconsistent in the terminal and GUI world
378 * copy and pasting. When receiving some selection data,
379 * replace all '\n' with '\r'.
380 * FIXME: Fix the computer world.
383 last = data + nitems * format / 8;
384 while ((repl = memchr(repl, '\n', last - repl))) {
388 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
389 ttywrite("\033[200~", 6);
390 ttysend((char *)data, nitems * format / 8);
391 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
392 ttywrite("\033[201~", 6);
394 /* number of 32-bit chunks returned */
395 ofs += nitems * format / 32;
399 * Deleting the property again tells the selection owner to send the
400 * next data chunk in the property.
402 XDeleteProperty(xw.dpy, xw.win, (int)property);
408 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
409 xw.win, CurrentTime);
417 if (sel.clipboard != NULL)
420 if (sel.primary != NULL) {
421 sel.clipboard = xstrdup(sel.primary);
422 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
423 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
432 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
433 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
434 xw.win, CurrentTime);
444 selrequest(XEvent *e)
446 XSelectionRequestEvent *xsre;
448 Atom xa_targets, string, clipboard;
451 xsre = (XSelectionRequestEvent *) e;
452 xev.type = SelectionNotify;
453 xev.requestor = xsre->requestor;
454 xev.selection = xsre->selection;
455 xev.target = xsre->target;
456 xev.time = xsre->time;
457 if (xsre->property == None)
458 xsre->property = xsre->target;
463 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
464 if (xsre->target == xa_targets) {
465 /* respond with the supported type */
466 string = xsel.xtarget;
467 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
468 XA_ATOM, 32, PropModeReplace,
469 (uchar *) &string, 1);
470 xev.property = xsre->property;
471 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
473 * xith XA_STRING non ascii characters may be incorrect in the
474 * requestor. It is not our problem, use utf8.
476 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
477 if (xsre->selection == XA_PRIMARY) {
478 seltext = sel.primary;
479 } else if (xsre->selection == clipboard) {
480 seltext = sel.clipboard;
483 "Unhandled clipboard selection 0x%lx\n",
487 if (seltext != NULL) {
488 XChangeProperty(xsre->display, xsre->requestor,
489 xsre->property, xsre->target,
491 (uchar *)seltext, strlen(seltext));
492 xev.property = xsre->property;
496 /* all done, send a notification to the listener */
497 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
498 fprintf(stderr, "Error sending SelectionNotify event\n");
502 xsetsel(char *str, Time t)
507 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
508 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
515 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
520 if (e->xbutton.button == Button2) {
522 } else if (e->xbutton.button == Button1) {
523 if (sel.mode == SEL_READY) {
525 selcopy(e->xbutton.time);
529 tsetdirt(sel.nb.y, sel.ne.y);
536 int oldey, oldex, oldsby, oldsey;
538 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
546 sel.mode = SEL_READY;
553 if (oldey != sel.oe.y || oldex != sel.oe.x)
554 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
558 xresize(int col, int row)
560 win.tw = MAX(1, col * win.cw);
561 win.th = MAX(1, row * win.ch);
563 XFreePixmap(xw.dpy, xw.buf);
564 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
565 DefaultDepth(xw.dpy, xw.scr));
566 XftDrawChange(xw.draw, xw.buf);
567 xclear(0, 0, win.w, win.h);
573 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
577 xloadcolor(int i, const char *name, Color *ncolor)
579 XRenderColor color = { .alpha = 0xffff };
582 if (BETWEEN(i, 16, 255)) { /* 256 color */
583 if (i < 6*6*6+16) { /* same colors as xterm */
584 color.red = sixd_to_16bit( ((i-16)/36)%6 );
585 color.green = sixd_to_16bit( ((i-16)/6) %6 );
586 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
587 } else { /* greyscale */
588 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
589 color.green = color.blue = color.red;
591 return XftColorAllocValue(xw.dpy, xw.vis,
592 xw.cmap, &color, ncolor);
597 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
607 dc.collen = MAX(colornamelen, 256);
608 dc.col = xmalloc(dc.collen * sizeof(Color));
611 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
612 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
615 for (i = 0; i < dc.collen; i++)
616 if (!xloadcolor(i, NULL, &dc.col[i])) {
618 die("Could not allocate color '%s'\n", colorname[i]);
620 die("Could not allocate color %d\n", i);
626 xsetcolorname(int x, const char *name)
630 if (!BETWEEN(x, 0, dc.collen))
634 if (!xloadcolor(x, name, &ncolor))
637 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
644 * Absolute coordinates.
647 xclear(int x1, int y1, int x2, int y2)
650 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
651 x1, y1, x2-x1, y2-y1);
657 XClassHint class = {opt_name ? opt_name : termname,
658 opt_class ? opt_class : termname};
659 XWMHints wm = {.flags = InputHint, .input = 1};
660 XSizeHints *sizeh = NULL;
662 sizeh = XAllocSizeHints();
664 sizeh->flags = PSize | PResizeInc | PBaseSize;
665 sizeh->height = win.h;
666 sizeh->width = win.w;
667 sizeh->height_inc = win.ch;
668 sizeh->width_inc = win.cw;
669 sizeh->base_height = 2 * borderpx;
670 sizeh->base_width = 2 * borderpx;
672 sizeh->flags |= PMaxSize | PMinSize;
673 sizeh->min_width = sizeh->max_width = win.w;
674 sizeh->min_height = sizeh->max_height = win.h;
676 if (xw.gm & (XValue|YValue)) {
677 sizeh->flags |= USPosition | PWinGravity;
680 sizeh->win_gravity = xgeommasktogravity(xw.gm);
683 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
689 xgeommasktogravity(int mask)
691 switch (mask & (XNegative|YNegative)) {
693 return NorthWestGravity;
695 return NorthEastGravity;
697 return SouthWestGravity;
700 return SouthEastGravity;
704 xloadfont(Font *f, FcPattern *pattern)
706 FcPattern *configured;
710 int wantattr, haveattr;
713 * Manually configure instead of calling XftMatchFont
714 * so that we can use the configured pattern for
715 * "missing glyph" lookups.
717 configured = FcPatternDuplicate(pattern);
721 FcConfigSubstitute(NULL, configured, FcMatchPattern);
722 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
724 match = FcFontMatch(NULL, configured, &result);
726 FcPatternDestroy(configured);
730 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
731 FcPatternDestroy(configured);
732 FcPatternDestroy(match);
736 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
739 * Check if xft was unable to find a font with the appropriate
740 * slant but gave us one anyway. Try to mitigate.
742 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
743 &haveattr) != XftResultMatch) || haveattr < wantattr) {
745 fputs("st: font slant does not match\n", stderr);
749 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
751 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
752 &haveattr) != XftResultMatch) || haveattr != wantattr) {
754 fputs("st: font weight does not match\n", stderr);
758 XftTextExtentsUtf8(xw.dpy, f->match,
759 (const FcChar8 *) ascii_printable,
760 strlen(ascii_printable), &extents);
763 f->pattern = configured;
765 f->ascent = f->match->ascent;
766 f->descent = f->match->descent;
768 f->rbearing = f->match->max_advance_width;
770 f->height = f->ascent + f->descent;
771 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
777 xloadfonts(char *fontstr, double fontsize)
783 if (fontstr[0] == '-') {
784 pattern = XftXlfdParse(fontstr, False, False);
786 pattern = FcNameParse((FcChar8 *)fontstr);
790 die("st: can't open font %s\n", fontstr);
793 FcPatternDel(pattern, FC_PIXEL_SIZE);
794 FcPatternDel(pattern, FC_SIZE);
795 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
796 usedfontsize = fontsize;
798 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
800 usedfontsize = fontval;
801 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
806 * Default font size is 12, if none given. This is to
807 * have a known usedfontsize value.
809 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
812 defaultfontsize = usedfontsize;
815 if (xloadfont(&dc.font, pattern))
816 die("st: can't open font %s\n", fontstr);
818 if (usedfontsize < 0) {
819 FcPatternGetDouble(dc.font.match->pattern,
820 FC_PIXEL_SIZE, 0, &fontval);
821 usedfontsize = fontval;
823 defaultfontsize = fontval;
826 /* Setting character width and height. */
827 win.cw = ceilf(dc.font.width * cwscale);
828 win.ch = ceilf(dc.font.height * chscale);
830 FcPatternDel(pattern, FC_SLANT);
831 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
832 if (xloadfont(&dc.ifont, pattern))
833 die("st: can't open font %s\n", fontstr);
835 FcPatternDel(pattern, FC_WEIGHT);
836 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
837 if (xloadfont(&dc.ibfont, pattern))
838 die("st: can't open font %s\n", fontstr);
840 FcPatternDel(pattern, FC_SLANT);
841 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
842 if (xloadfont(&dc.bfont, pattern))
843 die("st: can't open font %s\n", fontstr);
845 FcPatternDestroy(pattern);
851 XftFontClose(xw.dpy, f->match);
852 FcPatternDestroy(f->pattern);
854 FcFontSetDestroy(f->set);
860 /* Free the loaded fonts in the font cache. */
862 XftFontClose(xw.dpy, frc[--frclen].font);
864 xunloadfont(&dc.font);
865 xunloadfont(&dc.bfont);
866 xunloadfont(&dc.ifont);
867 xunloadfont(&dc.ibfont);
876 pid_t thispid = getpid();
877 XColor xmousefg, xmousebg;
879 if (!(xw.dpy = XOpenDisplay(NULL)))
880 die("Can't open display\n");
881 xw.scr = XDefaultScreen(xw.dpy);
882 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
886 die("Could not init fontconfig.\n");
888 usedfont = (opt_font == NULL)? font : opt_font;
889 xloadfonts(usedfont, 0);
892 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
895 /* adjust fixed window geometry */
896 win.w = 2 * borderpx + term.col * win.cw;
897 win.h = 2 * borderpx + term.row * win.ch;
898 if (xw.gm & XNegative)
899 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
900 if (xw.gm & YNegative)
901 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
904 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
905 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
906 xw.attrs.bit_gravity = NorthWestGravity;
907 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
908 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
909 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
910 xw.attrs.colormap = xw.cmap;
912 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
913 parent = XRootWindow(xw.dpy, xw.scr);
914 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
915 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
916 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
917 | CWEventMask | CWColormap, &xw.attrs);
919 memset(&gcvalues, 0, sizeof(gcvalues));
920 gcvalues.graphics_exposures = False;
921 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
923 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
924 DefaultDepth(xw.dpy, xw.scr));
925 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
926 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
928 /* Xft rendering context */
929 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
932 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
933 XSetLocaleModifiers("@im=local");
934 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
935 XSetLocaleModifiers("@im=");
936 if ((xw.xim = XOpenIM(xw.dpy,
937 NULL, NULL, NULL)) == NULL) {
938 die("XOpenIM failed. Could not open input"
943 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
944 | XIMStatusNothing, XNClientWindow, xw.win,
945 XNFocusWindow, xw.win, NULL);
947 die("XCreateIC failed. Could not obtain input method.\n");
949 /* white cursor, black outline */
950 cursor = XCreateFontCursor(xw.dpy, mouseshape);
951 XDefineCursor(xw.dpy, xw.win, cursor);
953 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
954 xmousefg.red = 0xffff;
955 xmousefg.green = 0xffff;
956 xmousefg.blue = 0xffff;
959 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
960 xmousebg.red = 0x0000;
961 xmousebg.green = 0x0000;
962 xmousebg.blue = 0x0000;
965 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
967 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
968 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
969 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
970 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
972 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
973 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
974 PropModeReplace, (uchar *)&thispid, 1);
977 XMapWindow(xw.dpy, xw.win);
979 XSync(xw.dpy, False);
981 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
982 if (xsel.xtarget == None)
983 xsel.xtarget = XA_STRING;
987 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
989 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
990 ushort mode, prevmode = USHRT_MAX;
991 Font *font = &dc.font;
992 int frcflags = FRC_NORMAL;
993 float runewidth = win.cw;
997 FcPattern *fcpattern, *fontpattern;
998 FcFontSet *fcsets[] = { NULL };
999 FcCharSet *fccharset;
1000 int i, f, numspecs = 0;
1002 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1003 /* Fetch rune and mode for current glyph. */
1005 mode = glyphs[i].mode;
1007 /* Skip dummy wide-character spacing. */
1008 if (mode == ATTR_WDUMMY)
1011 /* Determine font for glyph if different from previous glyph. */
1012 if (prevmode != mode) {
1015 frcflags = FRC_NORMAL;
1016 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1017 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1019 frcflags = FRC_ITALICBOLD;
1020 } else if (mode & ATTR_ITALIC) {
1022 frcflags = FRC_ITALIC;
1023 } else if (mode & ATTR_BOLD) {
1025 frcflags = FRC_BOLD;
1027 yp = winy + font->ascent;
1030 /* Lookup character index with default font. */
1031 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1033 specs[numspecs].font = font->match;
1034 specs[numspecs].glyph = glyphidx;
1035 specs[numspecs].x = (short)xp;
1036 specs[numspecs].y = (short)yp;
1042 /* Fallback on font cache, search the font cache for match. */
1043 for (f = 0; f < frclen; f++) {
1044 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1045 /* Everything correct. */
1046 if (glyphidx && frc[f].flags == frcflags)
1048 /* We got a default font for a not found glyph. */
1049 if (!glyphidx && frc[f].flags == frcflags
1050 && frc[f].unicodep == rune) {
1055 /* Nothing was found. Use fontconfig to find matching font. */
1058 font->set = FcFontSort(0, font->pattern,
1060 fcsets[0] = font->set;
1063 * Nothing was found in the cache. Now use
1064 * some dozen of Fontconfig calls to get the
1065 * font for one single character.
1067 * Xft and fontconfig are design failures.
1069 fcpattern = FcPatternDuplicate(font->pattern);
1070 fccharset = FcCharSetCreate();
1072 FcCharSetAddChar(fccharset, rune);
1073 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1075 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1077 FcConfigSubstitute(0, fcpattern,
1079 FcDefaultSubstitute(fcpattern);
1081 fontpattern = FcFontSetMatch(0, fcsets, 1,
1085 * Overwrite or create the new cache entry.
1087 if (frclen >= LEN(frc)) {
1088 frclen = LEN(frc) - 1;
1089 XftFontClose(xw.dpy, frc[frclen].font);
1090 frc[frclen].unicodep = 0;
1093 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1095 if (!frc[frclen].font)
1096 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1098 frc[frclen].flags = frcflags;
1099 frc[frclen].unicodep = rune;
1101 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1106 FcPatternDestroy(fcpattern);
1107 FcCharSetDestroy(fccharset);
1110 specs[numspecs].font = frc[f].font;
1111 specs[numspecs].glyph = glyphidx;
1112 specs[numspecs].x = (short)xp;
1113 specs[numspecs].y = (short)yp;
1122 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1124 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1125 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1126 width = charlen * win.cw;
1127 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1128 XRenderColor colfg, colbg;
1131 /* Fallback on color display for attributes not supported by the font */
1132 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1133 if (dc.ibfont.badslant || dc.ibfont.badweight)
1134 base.fg = defaultattr;
1135 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1136 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1137 base.fg = defaultattr;
1140 if (IS_TRUECOL(base.fg)) {
1141 colfg.alpha = 0xffff;
1142 colfg.red = TRUERED(base.fg);
1143 colfg.green = TRUEGREEN(base.fg);
1144 colfg.blue = TRUEBLUE(base.fg);
1145 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1148 fg = &dc.col[base.fg];
1151 if (IS_TRUECOL(base.bg)) {
1152 colbg.alpha = 0xffff;
1153 colbg.green = TRUEGREEN(base.bg);
1154 colbg.red = TRUERED(base.bg);
1155 colbg.blue = TRUEBLUE(base.bg);
1156 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1159 bg = &dc.col[base.bg];
1162 /* Change basic system colors [0-7] to bright system colors [8-15] */
1163 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1164 fg = &dc.col[base.fg + 8];
1166 if (IS_SET(MODE_REVERSE)) {
1167 if (fg == &dc.col[defaultfg]) {
1168 fg = &dc.col[defaultbg];
1170 colfg.red = ~fg->color.red;
1171 colfg.green = ~fg->color.green;
1172 colfg.blue = ~fg->color.blue;
1173 colfg.alpha = fg->color.alpha;
1174 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1179 if (bg == &dc.col[defaultbg]) {
1180 bg = &dc.col[defaultfg];
1182 colbg.red = ~bg->color.red;
1183 colbg.green = ~bg->color.green;
1184 colbg.blue = ~bg->color.blue;
1185 colbg.alpha = bg->color.alpha;
1186 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1192 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1193 colfg.red = fg->color.red / 2;
1194 colfg.green = fg->color.green / 2;
1195 colfg.blue = fg->color.blue / 2;
1196 colfg.alpha = fg->color.alpha;
1197 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1202 if (base.mode & ATTR_REVERSE) {
1208 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1211 if (base.mode & ATTR_INVISIBLE)
1214 /* Intelligent cleaning up of the borders. */
1216 xclear(0, (y == 0)? 0 : winy, borderpx,
1217 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1219 if (x + charlen >= term.col) {
1220 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1221 ((y >= term.row-1)? win.h : (winy + win.ch)));
1224 xclear(winx, 0, winx + width, borderpx);
1225 if (y == term.row-1)
1226 xclear(winx, winy + win.ch, winx + width, win.h);
1228 /* Clean up the region we want to draw to. */
1229 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1231 /* Set the clip region because Xft is sometimes dirty. */
1236 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1238 /* Render the glyphs. */
1239 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1241 /* Render underline and strikethrough. */
1242 if (base.mode & ATTR_UNDERLINE) {
1243 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1247 if (base.mode & ATTR_STRUCK) {
1248 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1252 /* Reset clip to none. */
1253 XftDrawSetClip(xw.draw, 0);
1257 xdrawglyph(Glyph g, int x, int y)
1260 XftGlyphFontSpec spec;
1262 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1263 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1269 static int oldx = 0, oldy = 0;
1271 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1272 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1275 LIMIT(oldx, 0, term.col-1);
1276 LIMIT(oldy, 0, term.row-1);
1280 /* adjust position if in dummy */
1281 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1283 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1286 /* remove the old cursor */
1287 og = term.line[oldy][oldx];
1288 if (ena_sel && selected(oldx, oldy))
1289 og.mode ^= ATTR_REVERSE;
1290 xdrawglyph(og, oldx, oldy);
1292 g.u = term.line[term.c.y][term.c.x].u;
1293 g.mode |= term.line[term.c.y][term.c.x].mode &
1294 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1297 * Select the right color for the right mode.
1299 if (IS_SET(MODE_REVERSE)) {
1300 g.mode |= ATTR_REVERSE;
1302 if (ena_sel && selected(term.c.x, term.c.y)) {
1303 drawcol = dc.col[defaultcs];
1306 drawcol = dc.col[defaultrcs];
1310 if (ena_sel && selected(term.c.x, term.c.y)) {
1311 drawcol = dc.col[defaultrcs];
1315 drawcol = dc.col[defaultcs];
1319 if (IS_SET(MODE_HIDE))
1322 /* draw the new one */
1323 if (win.state & WIN_FOCUSED) {
1324 switch (win.cursor) {
1325 case 7: /* st extension: snowman */
1326 utf8decode("☃", &g.u, UTF_SIZ);
1327 case 0: /* Blinking Block */
1328 case 1: /* Blinking Block (Default) */
1329 case 2: /* Steady Block */
1330 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1331 xdrawglyph(g, term.c.x, term.c.y);
1333 case 3: /* Blinking Underline */
1334 case 4: /* Steady Underline */
1335 XftDrawRect(xw.draw, &drawcol,
1336 borderpx + curx * win.cw,
1337 borderpx + (term.c.y + 1) * win.ch - \
1339 win.cw, cursorthickness);
1341 case 5: /* Blinking bar */
1342 case 6: /* Steady bar */
1343 XftDrawRect(xw.draw, &drawcol,
1344 borderpx + curx * win.cw,
1345 borderpx + term.c.y * win.ch,
1346 cursorthickness, win.ch);
1350 XftDrawRect(xw.draw, &drawcol,
1351 borderpx + curx * win.cw,
1352 borderpx + term.c.y * win.ch,
1354 XftDrawRect(xw.draw, &drawcol,
1355 borderpx + curx * win.cw,
1356 borderpx + term.c.y * win.ch,
1358 XftDrawRect(xw.draw, &drawcol,
1359 borderpx + (curx + 1) * win.cw - 1,
1360 borderpx + term.c.y * win.ch,
1362 XftDrawRect(xw.draw, &drawcol,
1363 borderpx + curx * win.cw,
1364 borderpx + (term.c.y + 1) * win.ch - 1,
1367 oldx = curx, oldy = term.c.y;
1373 char buf[sizeof(long) * 8 + 1];
1375 snprintf(buf, sizeof(buf), "%lu", xw.win);
1376 setenv("WINDOWID", buf, 1);
1384 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1386 XSetWMName(xw.dpy, xw.win, &prop);
1387 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1394 drawregion(0, 0, term.col, term.row);
1395 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1397 XSetForeground(xw.dpy, dc.gc,
1398 dc.col[IS_SET(MODE_REVERSE)?
1399 defaultfg : defaultbg].pixel);
1403 drawregion(int x1, int y1, int x2, int y2)
1405 int i, x, y, ox, numspecs;
1407 XftGlyphFontSpec *specs;
1408 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1410 if (!(win.state & WIN_VISIBLE))
1413 for (y = y1; y < y2; y++) {
1419 specs = term.specbuf;
1420 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1423 for (x = x1; x < x2 && i < numspecs; x++) {
1424 new = term.line[y][x];
1425 if (new.mode == ATTR_WDUMMY)
1427 if (ena_sel && selected(x, y))
1428 new.mode ^= ATTR_REVERSE;
1429 if (i > 0 && ATTRCMP(base, new)) {
1430 xdrawglyphfontspecs(specs, base, i, ox, y);
1442 xdrawglyphfontspecs(specs, base, i, ox, y);
1454 visibility(XEvent *ev)
1456 XVisibilityEvent *e = &ev->xvisibility;
1458 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1464 win.state &= ~WIN_VISIBLE;
1468 xsetpointermotion(int set)
1470 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1471 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1475 xseturgency(int add)
1477 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1479 MODBIT(h->flags, add, XUrgencyHint);
1480 XSetWMHints(xw.dpy, xw.win, h);
1487 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;
1707 main(int argc, char *argv[])
1711 win.cursor = cursorshape;
1718 opt_class = EARGF(usage());
1725 opt_font = EARGF(usage());
1728 xw.gm = XParseGeometry(EARGF(usage()),
1729 &xw.l, &xw.t, &cols, &rows);
1735 opt_io = EARGF(usage());
1738 opt_line = EARGF(usage());
1741 opt_name = EARGF(usage());
1745 opt_title = EARGF(usage());
1748 opt_embed = EARGF(usage());
1751 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1759 /* eat all remaining arguments */
1761 if (!opt_title && !opt_line)
1762 opt_title = basename(xstrdup(argv[0]));
1764 setlocale(LC_CTYPE, "");
1765 XSetLocaleModifiers("");
1766 tnew(MAX(cols, 1), MAX(rows, 1));