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>
24 #define XEMBED_FOCUS_IN 4
25 #define XEMBED_FOCUS_OUT 5
28 #define TRUERED(x) (((x) & 0xff0000) >> 8)
29 #define TRUEGREEN(x) (((x) & 0xff00))
30 #define TRUEBLUE(x) (((x) & 0xff) << 8)
32 typedef XftDraw *Draw;
33 typedef XftColor Color;
34 typedef XftGlyphFontSpec GlyphFontSpec;
36 /* Purely graphic info */
42 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
43 Atom xembed, wmdeletewin, netwmname, netwmpid;
48 XSetWindowAttributes attrs;
50 int isfixed; /* is fixed geometry? */
51 int l, t; /* left and top offset */
52 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 void xinit(void);
91 static int xloadfont(Font *, FcPattern *);
92 static void xloadfonts(char *, double);
93 static void xunloadfont(Font *);
94 static void xunloadfonts(void);
95 static void xsetenv(void);
96 static void xseturgency(int);
98 static void expose(XEvent *);
99 static void visibility(XEvent *);
100 static void unmap(XEvent *);
101 static void kpress(XEvent *);
102 static void cmessage(XEvent *);
103 static void resize(XEvent *);
104 static void focus(XEvent *);
105 static void brelease(XEvent *);
106 static void bpress(XEvent *);
107 static void bmotion(XEvent *);
108 static void propnotify(XEvent *);
109 static void selnotify(XEvent *);
110 static void selclear_(XEvent *);
111 static void selrequest(XEvent *);
113 static void selcopy(Time);
114 static void getbuttoninfo(XEvent *);
115 static void mousereport(XEvent *);
117 static void run(void);
118 static void usage(void);
120 static void (*handler[LASTEvent])(XEvent *) = {
122 [ClientMessage] = cmessage,
123 [ConfigureNotify] = resize,
124 [VisibilityNotify] = visibility,
125 [UnmapNotify] = unmap,
129 [MotionNotify] = bmotion,
130 [ButtonPress] = bpress,
131 [ButtonRelease] = brelease,
133 * Uncomment if you want the selection to disappear when you select something
134 * different in another window.
136 /* [SelectionClear] = selclear_, */
137 [SelectionNotify] = selnotify,
139 * PropertyNotify is only turned on when there is some INCR transfer happening
140 * for the selection retrieval.
142 [PropertyNotify] = propnotify,
143 [SelectionRequest] = selrequest,
149 static XSelection xsel;
151 /* Font Ring Cache */
165 /* Fontcache is an array now. A new font will be appended to the array. */
166 static Fontcache frc[16];
167 static int frclen = 0;
168 static char *usedfont = NULL;
169 static double usedfontsize = 0;
170 static double defaultfontsize = 0;
177 larg.f = usedfontsize + arg->f;
182 zoomabs(const Arg *arg)
185 xloadfonts(usedfont, arg->f);
193 zoomreset(const Arg *arg)
197 if (defaultfontsize > 0) {
198 larg.f = defaultfontsize;
204 getbuttoninfo(XEvent *e)
207 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
209 sel.alt = IS_SET(MODE_ALTSCREEN);
211 sel.oe.x = x2col(e->xbutton.x);
212 sel.oe.y = y2row(e->xbutton.y);
215 sel.type = SEL_REGULAR;
216 for (type = 1; type < selmaskslen; ++type) {
217 if (match(selmasks[type], state)) {
225 mousereport(XEvent *e)
227 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
228 button = e->xbutton.button, state = e->xbutton.state,
234 if (e->xbutton.type == MotionNotify) {
235 if (x == ox && y == oy)
237 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
239 /* MOUSE_MOTION: no reporting if no button is pressed */
240 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
243 button = oldbutton + 32;
247 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
254 if (e->xbutton.type == ButtonPress) {
258 } else if (e->xbutton.type == ButtonRelease) {
260 /* MODE_MOUSEX10: no button release reporting */
261 if (IS_SET(MODE_MOUSEX10))
263 if (button == 64 || button == 65)
268 if (!IS_SET(MODE_MOUSEX10)) {
269 button += ((state & ShiftMask ) ? 4 : 0)
270 + ((state & Mod4Mask ) ? 8 : 0)
271 + ((state & ControlMask) ? 16 : 0);
274 if (IS_SET(MODE_MOUSESGR)) {
275 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
277 e->xbutton.type == ButtonRelease ? 'm' : 'M');
278 } else if (x < 223 && y < 223) {
279 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
280 32+button, 32+x+1, 32+y+1);
294 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
299 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
300 if (e->xbutton.button == ms->b
301 && match(ms->mask, e->xbutton.state)) {
302 ttysend(ms->s, strlen(ms->s));
307 if (e->xbutton.button == Button1) {
308 clock_gettime(CLOCK_MONOTONIC, &now);
310 /* Clear previous selection, logically and visually. */
312 sel.mode = SEL_EMPTY;
313 sel.type = SEL_REGULAR;
314 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
315 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
318 * If the user clicks below predefined timeouts specific
319 * snapping behaviour is exposed.
321 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
322 sel.snap = SNAP_LINE;
323 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
324 sel.snap = SNAP_WORD;
331 sel.mode = SEL_READY;
332 tsetdirt(sel.nb.y, sel.ne.y);
333 sel.tclick2 = sel.tclick1;
341 xsetsel(getsel(), t);
345 propnotify(XEvent *e)
347 XPropertyEvent *xpev;
348 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
350 xpev = &e->xproperty;
351 if (xpev->state == PropertyNewValue &&
352 (xpev->atom == XA_PRIMARY ||
353 xpev->atom == clipboard)) {
361 ulong nitems, ofs, rem;
363 uchar *data, *last, *repl;
364 Atom type, incratom, property;
366 incratom = XInternAtom(xw.dpy, "INCR", 0);
369 if (e->type == SelectionNotify) {
370 property = e->xselection.property;
371 } else if(e->type == PropertyNotify) {
372 property = e->xproperty.atom;
376 if (property == None)
380 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
381 BUFSIZ/4, False, AnyPropertyType,
382 &type, &format, &nitems, &rem,
384 fprintf(stderr, "Clipboard allocation failed\n");
388 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
390 * If there is some PropertyNotify with no data, then
391 * this is the signal of the selection owner that all
392 * data has been transferred. We won't need to receive
393 * PropertyNotify events anymore.
395 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
396 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
400 if (type == incratom) {
402 * Activate the PropertyNotify events so we receive
403 * when the selection owner does send us the next
406 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
407 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
411 * Deleting the property is the transfer start signal.
413 XDeleteProperty(xw.dpy, xw.win, (int)property);
419 * Line endings are inconsistent in the terminal and GUI world
420 * copy and pasting. When receiving some selection data,
421 * replace all '\n' with '\r'.
422 * FIXME: Fix the computer world.
425 last = data + nitems * format / 8;
426 while ((repl = memchr(repl, '\n', last - repl))) {
430 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
431 ttywrite("\033[200~", 6);
432 ttysend((char *)data, nitems * format / 8);
433 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
434 ttywrite("\033[201~", 6);
436 /* number of 32-bit chunks returned */
437 ofs += nitems * format / 32;
441 * Deleting the property again tells the selection owner to send the
442 * next data chunk in the property.
444 XDeleteProperty(xw.dpy, xw.win, (int)property);
450 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
451 xw.win, CurrentTime);
459 if (sel.clipboard != NULL)
462 if (sel.primary != NULL) {
463 sel.clipboard = xstrdup(sel.primary);
464 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
465 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
474 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
475 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
476 xw.win, CurrentTime);
486 selrequest(XEvent *e)
488 XSelectionRequestEvent *xsre;
490 Atom xa_targets, string, clipboard;
493 xsre = (XSelectionRequestEvent *) e;
494 xev.type = SelectionNotify;
495 xev.requestor = xsre->requestor;
496 xev.selection = xsre->selection;
497 xev.target = xsre->target;
498 xev.time = xsre->time;
499 if (xsre->property == None)
500 xsre->property = xsre->target;
505 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
506 if (xsre->target == xa_targets) {
507 /* respond with the supported type */
508 string = xsel.xtarget;
509 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
510 XA_ATOM, 32, PropModeReplace,
511 (uchar *) &string, 1);
512 xev.property = xsre->property;
513 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
515 * xith XA_STRING non ascii characters may be incorrect in the
516 * requestor. It is not our problem, use utf8.
518 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
519 if (xsre->selection == XA_PRIMARY) {
520 seltext = sel.primary;
521 } else if (xsre->selection == clipboard) {
522 seltext = sel.clipboard;
525 "Unhandled clipboard selection 0x%lx\n",
529 if (seltext != NULL) {
530 XChangeProperty(xsre->display, xsre->requestor,
531 xsre->property, xsre->target,
533 (uchar *)seltext, strlen(seltext));
534 xev.property = xsre->property;
538 /* all done, send a notification to the listener */
539 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
540 fprintf(stderr, "Error sending SelectionNotify event\n");
544 xsetsel(char *str, Time t)
549 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
550 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
557 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
562 if (e->xbutton.button == Button2) {
564 } else if (e->xbutton.button == Button1) {
565 if (sel.mode == SEL_READY) {
567 selcopy(e->xbutton.time);
571 tsetdirt(sel.nb.y, sel.ne.y);
578 int oldey, oldex, oldsby, oldsey;
580 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
588 sel.mode = SEL_READY;
595 if (oldey != sel.oe.y || oldex != sel.oe.x)
596 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
600 xresize(int col, int row)
602 win.tw = MAX(1, col * win.cw);
603 win.th = MAX(1, row * win.ch);
605 XFreePixmap(xw.dpy, xw.buf);
606 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
607 DefaultDepth(xw.dpy, xw.scr));
608 XftDrawChange(xw.draw, xw.buf);
609 xclear(0, 0, win.w, win.h);
611 /* resize to new width */
612 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
618 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
622 xloadcolor(int i, const char *name, Color *ncolor)
624 XRenderColor color = { .alpha = 0xffff };
627 if (BETWEEN(i, 16, 255)) { /* 256 color */
628 if (i < 6*6*6+16) { /* same colors as xterm */
629 color.red = sixd_to_16bit( ((i-16)/36)%6 );
630 color.green = sixd_to_16bit( ((i-16)/6) %6 );
631 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
632 } else { /* greyscale */
633 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
634 color.green = color.blue = color.red;
636 return XftColorAllocValue(xw.dpy, xw.vis,
637 xw.cmap, &color, ncolor);
642 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
652 dc.collen = MAX(colornamelen, 256);
653 dc.col = xmalloc(dc.collen * sizeof(Color));
656 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
657 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
660 for (i = 0; i < dc.collen; i++)
661 if (!xloadcolor(i, NULL, &dc.col[i])) {
663 die("Could not allocate color '%s'\n", colorname[i]);
665 die("Could not allocate color %d\n", i);
671 xsetcolorname(int x, const char *name)
675 if (!BETWEEN(x, 0, dc.collen))
679 if (!xloadcolor(x, name, &ncolor))
682 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
689 * Absolute coordinates.
692 xclear(int x1, int y1, int x2, int y2)
695 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
696 x1, y1, x2-x1, y2-y1);
702 XClassHint class = {opt_name ? opt_name : termname,
703 opt_class ? opt_class : termname};
704 XWMHints wm = {.flags = InputHint, .input = 1};
705 XSizeHints *sizeh = NULL;
707 sizeh = XAllocSizeHints();
709 sizeh->flags = PSize | PResizeInc | PBaseSize;
710 sizeh->height = win.h;
711 sizeh->width = win.w;
712 sizeh->height_inc = win.ch;
713 sizeh->width_inc = win.cw;
714 sizeh->base_height = 2 * borderpx;
715 sizeh->base_width = 2 * borderpx;
717 sizeh->flags |= PMaxSize | PMinSize;
718 sizeh->min_width = sizeh->max_width = win.w;
719 sizeh->min_height = sizeh->max_height = win.h;
721 if (xw.gm & (XValue|YValue)) {
722 sizeh->flags |= USPosition | PWinGravity;
725 sizeh->win_gravity = xgeommasktogravity(xw.gm);
728 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
734 xgeommasktogravity(int mask)
736 switch (mask & (XNegative|YNegative)) {
738 return NorthWestGravity;
740 return NorthEastGravity;
742 return SouthWestGravity;
745 return SouthEastGravity;
749 xloadfont(Font *f, FcPattern *pattern)
751 FcPattern *configured;
755 int wantattr, haveattr;
758 * Manually configure instead of calling XftMatchFont
759 * so that we can use the configured pattern for
760 * "missing glyph" lookups.
762 configured = FcPatternDuplicate(pattern);
766 FcConfigSubstitute(NULL, configured, FcMatchPattern);
767 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
769 match = FcFontMatch(NULL, configured, &result);
771 FcPatternDestroy(configured);
775 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
776 FcPatternDestroy(configured);
777 FcPatternDestroy(match);
781 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
784 * Check if xft was unable to find a font with the appropriate
785 * slant but gave us one anyway. Try to mitigate.
787 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
788 &haveattr) != XftResultMatch) || haveattr < wantattr) {
790 fputs("st: font slant does not match\n", stderr);
794 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
796 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
797 &haveattr) != XftResultMatch) || haveattr != wantattr) {
799 fputs("st: font weight does not match\n", stderr);
803 XftTextExtentsUtf8(xw.dpy, f->match,
804 (const FcChar8 *) ascii_printable,
805 strlen(ascii_printable), &extents);
808 f->pattern = configured;
810 f->ascent = f->match->ascent;
811 f->descent = f->match->descent;
813 f->rbearing = f->match->max_advance_width;
815 f->height = f->ascent + f->descent;
816 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
822 xloadfonts(char *fontstr, double fontsize)
828 if (fontstr[0] == '-') {
829 pattern = XftXlfdParse(fontstr, False, False);
831 pattern = FcNameParse((FcChar8 *)fontstr);
835 die("st: can't open font %s\n", fontstr);
838 FcPatternDel(pattern, FC_PIXEL_SIZE);
839 FcPatternDel(pattern, FC_SIZE);
840 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
841 usedfontsize = fontsize;
843 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
845 usedfontsize = fontval;
846 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
851 * Default font size is 12, if none given. This is to
852 * have a known usedfontsize value.
854 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
857 defaultfontsize = usedfontsize;
860 if (xloadfont(&dc.font, pattern))
861 die("st: can't open font %s\n", fontstr);
863 if (usedfontsize < 0) {
864 FcPatternGetDouble(dc.font.match->pattern,
865 FC_PIXEL_SIZE, 0, &fontval);
866 usedfontsize = fontval;
868 defaultfontsize = fontval;
871 /* Setting character width and height. */
872 win.cw = ceilf(dc.font.width * cwscale);
873 win.ch = ceilf(dc.font.height * chscale);
875 FcPatternDel(pattern, FC_SLANT);
876 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
877 if (xloadfont(&dc.ifont, pattern))
878 die("st: can't open font %s\n", fontstr);
880 FcPatternDel(pattern, FC_WEIGHT);
881 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
882 if (xloadfont(&dc.ibfont, pattern))
883 die("st: can't open font %s\n", fontstr);
885 FcPatternDel(pattern, FC_SLANT);
886 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
887 if (xloadfont(&dc.bfont, pattern))
888 die("st: can't open font %s\n", fontstr);
890 FcPatternDestroy(pattern);
896 XftFontClose(xw.dpy, f->match);
897 FcPatternDestroy(f->pattern);
899 FcFontSetDestroy(f->set);
905 /* Free the loaded fonts in the font cache. */
907 XftFontClose(xw.dpy, frc[--frclen].font);
909 xunloadfont(&dc.font);
910 xunloadfont(&dc.bfont);
911 xunloadfont(&dc.ifont);
912 xunloadfont(&dc.ibfont);
921 pid_t thispid = getpid();
922 XColor xmousefg, xmousebg;
924 if (!(xw.dpy = XOpenDisplay(NULL)))
925 die("Can't open display\n");
926 xw.scr = XDefaultScreen(xw.dpy);
927 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
931 die("Could not init fontconfig.\n");
933 usedfont = (opt_font == NULL)? font : opt_font;
934 xloadfonts(usedfont, 0);
937 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
940 /* adjust fixed window geometry */
941 win.w = 2 * borderpx + term.col * win.cw;
942 win.h = 2 * borderpx + term.row * win.ch;
943 if (xw.gm & XNegative)
944 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
945 if (xw.gm & YNegative)
946 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
949 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
950 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
951 xw.attrs.bit_gravity = NorthWestGravity;
952 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
953 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
954 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
955 xw.attrs.colormap = xw.cmap;
957 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
958 parent = XRootWindow(xw.dpy, xw.scr);
959 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
960 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
961 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
962 | CWEventMask | CWColormap, &xw.attrs);
964 memset(&gcvalues, 0, sizeof(gcvalues));
965 gcvalues.graphics_exposures = False;
966 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
968 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
969 DefaultDepth(xw.dpy, xw.scr));
970 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
971 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
973 /* font spec buffer */
974 xw.specbuf = xmalloc(term.col * sizeof(GlyphFontSpec));
976 /* Xft rendering context */
977 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
980 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
981 XSetLocaleModifiers("@im=local");
982 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
983 XSetLocaleModifiers("@im=");
984 if ((xw.xim = XOpenIM(xw.dpy,
985 NULL, NULL, NULL)) == NULL) {
986 die("XOpenIM failed. Could not open input"
991 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
992 | XIMStatusNothing, XNClientWindow, xw.win,
993 XNFocusWindow, xw.win, NULL);
995 die("XCreateIC failed. Could not obtain input method.\n");
997 /* white cursor, black outline */
998 cursor = XCreateFontCursor(xw.dpy, mouseshape);
999 XDefineCursor(xw.dpy, xw.win, cursor);
1001 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1002 xmousefg.red = 0xffff;
1003 xmousefg.green = 0xffff;
1004 xmousefg.blue = 0xffff;
1007 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1008 xmousebg.red = 0x0000;
1009 xmousebg.green = 0x0000;
1010 xmousebg.blue = 0x0000;
1013 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1015 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1016 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1017 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1018 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1020 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1021 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1022 PropModeReplace, (uchar *)&thispid, 1);
1025 XMapWindow(xw.dpy, xw.win);
1027 XSync(xw.dpy, False);
1029 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1030 if (xsel.xtarget == None)
1031 xsel.xtarget = XA_STRING;
1035 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1037 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1038 ushort mode, prevmode = USHRT_MAX;
1039 Font *font = &dc.font;
1040 int frcflags = FRC_NORMAL;
1041 float runewidth = win.cw;
1045 FcPattern *fcpattern, *fontpattern;
1046 FcFontSet *fcsets[] = { NULL };
1047 FcCharSet *fccharset;
1048 int i, f, numspecs = 0;
1050 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1051 /* Fetch rune and mode for current glyph. */
1053 mode = glyphs[i].mode;
1055 /* Skip dummy wide-character spacing. */
1056 if (mode == ATTR_WDUMMY)
1059 /* Determine font for glyph if different from previous glyph. */
1060 if (prevmode != mode) {
1063 frcflags = FRC_NORMAL;
1064 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1065 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1067 frcflags = FRC_ITALICBOLD;
1068 } else if (mode & ATTR_ITALIC) {
1070 frcflags = FRC_ITALIC;
1071 } else if (mode & ATTR_BOLD) {
1073 frcflags = FRC_BOLD;
1075 yp = winy + font->ascent;
1078 /* Lookup character index with default font. */
1079 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1081 specs[numspecs].font = font->match;
1082 specs[numspecs].glyph = glyphidx;
1083 specs[numspecs].x = (short)xp;
1084 specs[numspecs].y = (short)yp;
1090 /* Fallback on font cache, search the font cache for match. */
1091 for (f = 0; f < frclen; f++) {
1092 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1093 /* Everything correct. */
1094 if (glyphidx && frc[f].flags == frcflags)
1096 /* We got a default font for a not found glyph. */
1097 if (!glyphidx && frc[f].flags == frcflags
1098 && frc[f].unicodep == rune) {
1103 /* Nothing was found. Use fontconfig to find matching font. */
1106 font->set = FcFontSort(0, font->pattern,
1108 fcsets[0] = font->set;
1111 * Nothing was found in the cache. Now use
1112 * some dozen of Fontconfig calls to get the
1113 * font for one single character.
1115 * Xft and fontconfig are design failures.
1117 fcpattern = FcPatternDuplicate(font->pattern);
1118 fccharset = FcCharSetCreate();
1120 FcCharSetAddChar(fccharset, rune);
1121 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1123 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1125 FcConfigSubstitute(0, fcpattern,
1127 FcDefaultSubstitute(fcpattern);
1129 fontpattern = FcFontSetMatch(0, fcsets, 1,
1133 * Overwrite or create the new cache entry.
1135 if (frclen >= LEN(frc)) {
1136 frclen = LEN(frc) - 1;
1137 XftFontClose(xw.dpy, frc[frclen].font);
1138 frc[frclen].unicodep = 0;
1141 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1143 if (!frc[frclen].font)
1144 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1146 frc[frclen].flags = frcflags;
1147 frc[frclen].unicodep = rune;
1149 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1154 FcPatternDestroy(fcpattern);
1155 FcCharSetDestroy(fccharset);
1158 specs[numspecs].font = frc[f].font;
1159 specs[numspecs].glyph = glyphidx;
1160 specs[numspecs].x = (short)xp;
1161 specs[numspecs].y = (short)yp;
1170 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1172 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1173 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1174 width = charlen * win.cw;
1175 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1176 XRenderColor colfg, colbg;
1179 /* Fallback on color display for attributes not supported by the font */
1180 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1181 if (dc.ibfont.badslant || dc.ibfont.badweight)
1182 base.fg = defaultattr;
1183 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1184 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1185 base.fg = defaultattr;
1188 if (IS_TRUECOL(base.fg)) {
1189 colfg.alpha = 0xffff;
1190 colfg.red = TRUERED(base.fg);
1191 colfg.green = TRUEGREEN(base.fg);
1192 colfg.blue = TRUEBLUE(base.fg);
1193 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1196 fg = &dc.col[base.fg];
1199 if (IS_TRUECOL(base.bg)) {
1200 colbg.alpha = 0xffff;
1201 colbg.green = TRUEGREEN(base.bg);
1202 colbg.red = TRUERED(base.bg);
1203 colbg.blue = TRUEBLUE(base.bg);
1204 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1207 bg = &dc.col[base.bg];
1210 /* Change basic system colors [0-7] to bright system colors [8-15] */
1211 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1212 fg = &dc.col[base.fg + 8];
1214 if (IS_SET(MODE_REVERSE)) {
1215 if (fg == &dc.col[defaultfg]) {
1216 fg = &dc.col[defaultbg];
1218 colfg.red = ~fg->color.red;
1219 colfg.green = ~fg->color.green;
1220 colfg.blue = ~fg->color.blue;
1221 colfg.alpha = fg->color.alpha;
1222 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1227 if (bg == &dc.col[defaultbg]) {
1228 bg = &dc.col[defaultfg];
1230 colbg.red = ~bg->color.red;
1231 colbg.green = ~bg->color.green;
1232 colbg.blue = ~bg->color.blue;
1233 colbg.alpha = bg->color.alpha;
1234 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1240 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1241 colfg.red = fg->color.red / 2;
1242 colfg.green = fg->color.green / 2;
1243 colfg.blue = fg->color.blue / 2;
1244 colfg.alpha = fg->color.alpha;
1245 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1250 if (base.mode & ATTR_REVERSE) {
1256 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1259 if (base.mode & ATTR_INVISIBLE)
1262 /* Intelligent cleaning up of the borders. */
1264 xclear(0, (y == 0)? 0 : winy, borderpx,
1265 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1267 if (x + charlen >= term.col) {
1268 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1269 ((y >= term.row-1)? win.h : (winy + win.ch)));
1272 xclear(winx, 0, winx + width, borderpx);
1273 if (y == term.row-1)
1274 xclear(winx, winy + win.ch, winx + width, win.h);
1276 /* Clean up the region we want to draw to. */
1277 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1279 /* Set the clip region because Xft is sometimes dirty. */
1284 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1286 /* Render the glyphs. */
1287 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1289 /* Render underline and strikethrough. */
1290 if (base.mode & ATTR_UNDERLINE) {
1291 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1295 if (base.mode & ATTR_STRUCK) {
1296 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1300 /* Reset clip to none. */
1301 XftDrawSetClip(xw.draw, 0);
1305 xdrawglyph(Glyph g, int x, int y)
1308 XftGlyphFontSpec spec;
1310 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1311 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1317 static int oldx = 0, oldy = 0;
1319 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1320 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1323 LIMIT(oldx, 0, term.col-1);
1324 LIMIT(oldy, 0, term.row-1);
1328 /* adjust position if in dummy */
1329 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1331 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1334 /* remove the old cursor */
1335 og = term.line[oldy][oldx];
1336 if (ena_sel && selected(oldx, oldy))
1337 og.mode ^= ATTR_REVERSE;
1338 xdrawglyph(og, oldx, oldy);
1340 g.u = term.line[term.c.y][term.c.x].u;
1341 g.mode |= term.line[term.c.y][term.c.x].mode &
1342 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1345 * Select the right color for the right mode.
1347 if (IS_SET(MODE_REVERSE)) {
1348 g.mode |= ATTR_REVERSE;
1350 if (ena_sel && selected(term.c.x, term.c.y)) {
1351 drawcol = dc.col[defaultcs];
1354 drawcol = dc.col[defaultrcs];
1358 if (ena_sel && selected(term.c.x, term.c.y)) {
1359 drawcol = dc.col[defaultrcs];
1363 drawcol = dc.col[defaultcs];
1367 if (IS_SET(MODE_HIDE))
1370 /* draw the new one */
1371 if (win.state & WIN_FOCUSED) {
1372 switch (win.cursor) {
1373 case 7: /* st extension: snowman */
1374 utf8decode("☃", &g.u, UTF_SIZ);
1375 case 0: /* Blinking Block */
1376 case 1: /* Blinking Block (Default) */
1377 case 2: /* Steady Block */
1378 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1379 xdrawglyph(g, term.c.x, term.c.y);
1381 case 3: /* Blinking Underline */
1382 case 4: /* Steady Underline */
1383 XftDrawRect(xw.draw, &drawcol,
1384 borderpx + curx * win.cw,
1385 borderpx + (term.c.y + 1) * win.ch - \
1387 win.cw, cursorthickness);
1389 case 5: /* Blinking bar */
1390 case 6: /* Steady bar */
1391 XftDrawRect(xw.draw, &drawcol,
1392 borderpx + curx * win.cw,
1393 borderpx + term.c.y * win.ch,
1394 cursorthickness, win.ch);
1398 XftDrawRect(xw.draw, &drawcol,
1399 borderpx + curx * win.cw,
1400 borderpx + term.c.y * win.ch,
1402 XftDrawRect(xw.draw, &drawcol,
1403 borderpx + curx * win.cw,
1404 borderpx + term.c.y * win.ch,
1406 XftDrawRect(xw.draw, &drawcol,
1407 borderpx + (curx + 1) * win.cw - 1,
1408 borderpx + term.c.y * win.ch,
1410 XftDrawRect(xw.draw, &drawcol,
1411 borderpx + curx * win.cw,
1412 borderpx + (term.c.y + 1) * win.ch - 1,
1415 oldx = curx, oldy = term.c.y;
1421 char buf[sizeof(long) * 8 + 1];
1423 snprintf(buf, sizeof(buf), "%lu", xw.win);
1424 setenv("WINDOWID", buf, 1);
1432 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1434 XSetWMName(xw.dpy, xw.win, &prop);
1435 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1442 drawregion(0, 0, term.col, term.row);
1443 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1445 XSetForeground(xw.dpy, dc.gc,
1446 dc.col[IS_SET(MODE_REVERSE)?
1447 defaultfg : defaultbg].pixel);
1451 drawregion(int x1, int y1, int x2, int y2)
1453 int i, x, y, ox, numspecs;
1455 XftGlyphFontSpec *specs;
1456 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1458 if (!(win.state & WIN_VISIBLE))
1461 for (y = y1; y < y2; y++) {
1468 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1471 for (x = x1; x < x2 && i < numspecs; x++) {
1472 new = term.line[y][x];
1473 if (new.mode == ATTR_WDUMMY)
1475 if (ena_sel && selected(x, y))
1476 new.mode ^= ATTR_REVERSE;
1477 if (i > 0 && ATTRCMP(base, new)) {
1478 xdrawglyphfontspecs(specs, base, i, ox, y);
1490 xdrawglyphfontspecs(specs, base, i, ox, y);
1502 visibility(XEvent *ev)
1504 XVisibilityEvent *e = &ev->xvisibility;
1506 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1512 win.state &= ~WIN_VISIBLE;
1516 xsetpointermotion(int set)
1518 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1519 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1523 xseturgency(int add)
1525 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1527 MODBIT(h->flags, add, XUrgencyHint);
1528 XSetWMHints(xw.dpy, xw.win, h);
1535 if (!(win.state & WIN_FOCUSED))
1538 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1544 XFocusChangeEvent *e = &ev->xfocus;
1546 if (e->mode == NotifyGrab)
1549 if (ev->type == FocusIn) {
1550 XSetICFocus(xw.xic);
1551 win.state |= WIN_FOCUSED;
1553 if (IS_SET(MODE_FOCUS))
1554 ttywrite("\033[I", 3);
1556 XUnsetICFocus(xw.xic);
1557 win.state &= ~WIN_FOCUSED;
1558 if (IS_SET(MODE_FOCUS))
1559 ttywrite("\033[O", 3);
1566 XKeyEvent *e = &ev->xkey;
1568 char buf[32], *customkey;
1574 if (IS_SET(MODE_KBDLOCK))
1577 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1579 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1580 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1581 bp->func(&(bp->arg));
1586 /* 2. custom keys from config.h */
1587 if ((customkey = kmap(ksym, e->state))) {
1588 ttysend(customkey, strlen(customkey));
1592 /* 3. composed string from input method */
1595 if (len == 1 && e->state & Mod1Mask) {
1596 if (IS_SET(MODE_8BIT)) {
1599 len = utf8encode(c, buf);
1616 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1618 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1619 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1620 win.state |= WIN_FOCUSED;
1622 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1623 win.state &= ~WIN_FOCUSED;
1625 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1626 /* Send SIGHUP to shell */
1635 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1638 cresize(e->xconfigure.width, e->xconfigure.height);
1646 int w = win.w, h = win.h;
1648 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1649 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1652 /* Waiting for window mapping */
1654 XNextEvent(xw.dpy, &ev);
1656 * This XFilterEvent call is required because of XOpenIM. It
1657 * does filter out the key event and some client message for
1658 * the input method too.
1660 if (XFilterEvent(&ev, None))
1662 if (ev.type == ConfigureNotify) {
1663 w = ev.xconfigure.width;
1664 h = ev.xconfigure.height;
1666 } while (ev.type != MapNotify);
1672 clock_gettime(CLOCK_MONOTONIC, &last);
1675 for (xev = actionfps;;) {
1677 FD_SET(cmdfd, &rfd);
1680 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1683 die("select failed: %s\n", strerror(errno));
1685 if (FD_ISSET(cmdfd, &rfd)) {
1688 blinkset = tattrset(ATTR_BLINK);
1690 MODBIT(term.mode, 0, MODE_BLINK);
1694 if (FD_ISSET(xfd, &rfd))
1697 clock_gettime(CLOCK_MONOTONIC, &now);
1698 drawtimeout.tv_sec = 0;
1699 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1703 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1704 tsetdirtattr(ATTR_BLINK);
1705 term.mode ^= MODE_BLINK;
1709 deltatime = TIMEDIFF(now, last);
1710 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1716 while (XPending(xw.dpy)) {
1717 XNextEvent(xw.dpy, &ev);
1718 if (XFilterEvent(&ev, None))
1720 if (handler[ev.type])
1721 (handler[ev.type])(&ev);
1727 if (xev && !FD_ISSET(xfd, &rfd))
1729 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1731 if (TIMEDIFF(now, lastblink) \
1733 drawtimeout.tv_nsec = 1000;
1735 drawtimeout.tv_nsec = (1E6 * \
1740 drawtimeout.tv_sec = \
1741 drawtimeout.tv_nsec / 1E9;
1742 drawtimeout.tv_nsec %= (long)1E9;
1754 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1755 " [-n name] [-o file]\n"
1756 " [-T title] [-t title] [-w windowid]"
1757 " [[-e] command [args ...]]\n"
1758 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1759 " [-n name] [-o file]\n"
1760 " [-T title] [-t title] [-w windowid] -l line"
1761 " [stty_args ...]\n", argv0, argv0);
1765 main(int argc, char *argv[])
1769 win.cursor = cursorshape;
1776 opt_class = EARGF(usage());
1783 opt_font = EARGF(usage());
1786 xw.gm = XParseGeometry(EARGF(usage()),
1787 &xw.l, &xw.t, &cols, &rows);
1793 opt_io = EARGF(usage());
1796 opt_line = EARGF(usage());
1799 opt_name = EARGF(usage());
1803 opt_title = EARGF(usage());
1806 opt_embed = EARGF(usage());
1809 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1817 /* eat all remaining arguments */
1819 if (!opt_title && !opt_line)
1820 opt_title = basename(xstrdup(argv[0]));
1822 setlocale(LC_CTYPE, "");
1823 XSetLocaleModifiers("");
1824 tnew(MAX(cols, 1), MAX(rows, 1));