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 void cresize(int, int);
92 static void xresize(int, int);
93 static int xloadfont(Font *, FcPattern *);
94 static void xloadfonts(char *, double);
95 static void xunloadfont(Font *);
96 static void xunloadfonts(void);
97 static void xsetenv(void);
98 static void xseturgency(int);
99 static int x2col(int);
100 static int y2row(int);
102 static void expose(XEvent *);
103 static void visibility(XEvent *);
104 static void unmap(XEvent *);
105 static void kpress(XEvent *);
106 static void cmessage(XEvent *);
107 static void resize(XEvent *);
108 static void focus(XEvent *);
109 static void brelease(XEvent *);
110 static void bpress(XEvent *);
111 static void bmotion(XEvent *);
112 static void propnotify(XEvent *);
113 static void selnotify(XEvent *);
114 static void selclear_(XEvent *);
115 static void selrequest(XEvent *);
116 static void selcopy(Time);
117 static void getbuttoninfo(XEvent *);
118 static void mousereport(XEvent *);
119 static char *kmap(KeySym, uint);
120 static int match(uint, uint);
122 static void run(void);
123 static void usage(void);
125 static void (*handler[LASTEvent])(XEvent *) = {
127 [ClientMessage] = cmessage,
128 [ConfigureNotify] = resize,
129 [VisibilityNotify] = visibility,
130 [UnmapNotify] = unmap,
134 [MotionNotify] = bmotion,
135 [ButtonPress] = bpress,
136 [ButtonRelease] = brelease,
138 * Uncomment if you want the selection to disappear when you select something
139 * different in another window.
141 /* [SelectionClear] = selclear_, */
142 [SelectionNotify] = selnotify,
144 * PropertyNotify is only turned on when there is some INCR transfer happening
145 * for the selection retrieval.
147 [PropertyNotify] = propnotify,
148 [SelectionRequest] = selrequest,
154 static XSelection xsel;
161 /* Font Ring Cache */
175 /* Fontcache is an array now. A new font will be appended to the array. */
176 static Fontcache frc[16];
177 static int frclen = 0;
178 static char *usedfont = NULL;
179 static double usedfontsize = 0;
180 static double defaultfontsize = 0;
187 larg.f = usedfontsize + arg->f;
192 zoomabs(const Arg *arg)
195 xloadfonts(usedfont, arg->f);
197 ttyresize(win.tw, win.th);
203 zoomreset(const Arg *arg)
207 if (defaultfontsize > 0) {
208 larg.f = defaultfontsize;
219 return LIMIT(x, 0, term.col-1);
228 return LIMIT(y, 0, term.row-1);
232 getbuttoninfo(XEvent *e)
235 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
237 sel.alt = IS_SET(MODE_ALTSCREEN);
239 sel.oe.x = x2col(e->xbutton.x);
240 sel.oe.y = y2row(e->xbutton.y);
243 sel.type = SEL_REGULAR;
244 for (type = 1; type < selmaskslen; ++type) {
245 if (match(selmasks[type], state)) {
253 mousereport(XEvent *e)
255 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
256 button = e->xbutton.button, state = e->xbutton.state,
262 if (e->xbutton.type == MotionNotify) {
263 if (x == ox && y == oy)
265 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
267 /* MOUSE_MOTION: no reporting if no button is pressed */
268 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
271 button = oldbutton + 32;
275 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
282 if (e->xbutton.type == ButtonPress) {
286 } else if (e->xbutton.type == ButtonRelease) {
288 /* MODE_MOUSEX10: no button release reporting */
289 if (IS_SET(MODE_MOUSEX10))
291 if (button == 64 || button == 65)
296 if (!IS_SET(MODE_MOUSEX10)) {
297 button += ((state & ShiftMask ) ? 4 : 0)
298 + ((state & Mod4Mask ) ? 8 : 0)
299 + ((state & ControlMask) ? 16 : 0);
302 if (IS_SET(MODE_MOUSESGR)) {
303 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
305 e->xbutton.type == ButtonRelease ? 'm' : 'M');
306 } else if (x < 223 && y < 223) {
307 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
308 32+button, 32+x+1, 32+y+1);
322 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
327 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
328 if (e->xbutton.button == ms->b
329 && match(ms->mask, e->xbutton.state)) {
330 ttysend(ms->s, strlen(ms->s));
335 if (e->xbutton.button == Button1) {
336 clock_gettime(CLOCK_MONOTONIC, &now);
338 /* Clear previous selection, logically and visually. */
340 sel.mode = SEL_EMPTY;
341 sel.type = SEL_REGULAR;
342 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
343 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
346 * If the user clicks below predefined timeouts specific
347 * snapping behaviour is exposed.
349 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
350 sel.snap = SNAP_LINE;
351 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
352 sel.snap = SNAP_WORD;
359 sel.mode = SEL_READY;
360 tsetdirt(sel.nb.y, sel.ne.y);
361 sel.tclick2 = sel.tclick1;
369 xsetsel(getsel(), t);
373 propnotify(XEvent *e)
375 XPropertyEvent *xpev;
376 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
378 xpev = &e->xproperty;
379 if (xpev->state == PropertyNewValue &&
380 (xpev->atom == XA_PRIMARY ||
381 xpev->atom == clipboard)) {
389 ulong nitems, ofs, rem;
391 uchar *data, *last, *repl;
392 Atom type, incratom, property;
394 incratom = XInternAtom(xw.dpy, "INCR", 0);
397 if (e->type == SelectionNotify) {
398 property = e->xselection.property;
399 } else if(e->type == PropertyNotify) {
400 property = e->xproperty.atom;
404 if (property == None)
408 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
409 BUFSIZ/4, False, AnyPropertyType,
410 &type, &format, &nitems, &rem,
412 fprintf(stderr, "Clipboard allocation failed\n");
416 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
418 * If there is some PropertyNotify with no data, then
419 * this is the signal of the selection owner that all
420 * data has been transferred. We won't need to receive
421 * PropertyNotify events anymore.
423 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
424 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
428 if (type == incratom) {
430 * Activate the PropertyNotify events so we receive
431 * when the selection owner does send us the next
434 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
435 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
439 * Deleting the property is the transfer start signal.
441 XDeleteProperty(xw.dpy, xw.win, (int)property);
447 * Line endings are inconsistent in the terminal and GUI world
448 * copy and pasting. When receiving some selection data,
449 * replace all '\n' with '\r'.
450 * FIXME: Fix the computer world.
453 last = data + nitems * format / 8;
454 while ((repl = memchr(repl, '\n', last - repl))) {
458 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
459 ttywrite("\033[200~", 6);
460 ttysend((char *)data, nitems * format / 8);
461 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
462 ttywrite("\033[201~", 6);
464 /* number of 32-bit chunks returned */
465 ofs += nitems * format / 32;
469 * Deleting the property again tells the selection owner to send the
470 * next data chunk in the property.
472 XDeleteProperty(xw.dpy, xw.win, (int)property);
478 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
479 xw.win, CurrentTime);
487 if (sel.clipboard != NULL)
490 if (sel.primary != NULL) {
491 sel.clipboard = xstrdup(sel.primary);
492 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
493 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
502 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
503 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
504 xw.win, CurrentTime);
514 selrequest(XEvent *e)
516 XSelectionRequestEvent *xsre;
518 Atom xa_targets, string, clipboard;
521 xsre = (XSelectionRequestEvent *) e;
522 xev.type = SelectionNotify;
523 xev.requestor = xsre->requestor;
524 xev.selection = xsre->selection;
525 xev.target = xsre->target;
526 xev.time = xsre->time;
527 if (xsre->property == None)
528 xsre->property = xsre->target;
533 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
534 if (xsre->target == xa_targets) {
535 /* respond with the supported type */
536 string = xsel.xtarget;
537 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
538 XA_ATOM, 32, PropModeReplace,
539 (uchar *) &string, 1);
540 xev.property = xsre->property;
541 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
543 * xith XA_STRING non ascii characters may be incorrect in the
544 * requestor. It is not our problem, use utf8.
546 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
547 if (xsre->selection == XA_PRIMARY) {
548 seltext = sel.primary;
549 } else if (xsre->selection == clipboard) {
550 seltext = sel.clipboard;
553 "Unhandled clipboard selection 0x%lx\n",
557 if (seltext != NULL) {
558 XChangeProperty(xsre->display, xsre->requestor,
559 xsre->property, xsre->target,
561 (uchar *)seltext, strlen(seltext));
562 xev.property = xsre->property;
566 /* all done, send a notification to the listener */
567 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
568 fprintf(stderr, "Error sending SelectionNotify event\n");
572 xsetsel(char *str, Time t)
577 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
578 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
585 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
590 if (e->xbutton.button == Button2) {
592 } else if (e->xbutton.button == Button1) {
593 if (sel.mode == SEL_READY) {
595 selcopy(e->xbutton.time);
599 tsetdirt(sel.nb.y, sel.ne.y);
606 int oldey, oldex, oldsby, oldsey;
608 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
616 sel.mode = SEL_READY;
623 if (oldey != sel.oe.y || oldex != sel.oe.x)
624 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
628 cresize(int width, int height)
637 col = (win.w - 2 * borderpx) / win.cw;
638 row = (win.h - 2 * borderpx) / win.ch;
645 xresize(int col, int row)
647 win.tw = MAX(1, col * win.cw);
648 win.th = MAX(1, row * win.ch);
650 XFreePixmap(xw.dpy, xw.buf);
651 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
652 DefaultDepth(xw.dpy, xw.scr));
653 XftDrawChange(xw.draw, xw.buf);
654 xclear(0, 0, win.w, win.h);
656 /* resize to new width */
657 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
663 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
667 xloadcolor(int i, const char *name, Color *ncolor)
669 XRenderColor color = { .alpha = 0xffff };
672 if (BETWEEN(i, 16, 255)) { /* 256 color */
673 if (i < 6*6*6+16) { /* same colors as xterm */
674 color.red = sixd_to_16bit( ((i-16)/36)%6 );
675 color.green = sixd_to_16bit( ((i-16)/6) %6 );
676 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
677 } else { /* greyscale */
678 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
679 color.green = color.blue = color.red;
681 return XftColorAllocValue(xw.dpy, xw.vis,
682 xw.cmap, &color, ncolor);
687 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
697 dc.collen = MAX(colornamelen, 256);
698 dc.col = xmalloc(dc.collen * sizeof(Color));
701 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
702 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
705 for (i = 0; i < dc.collen; i++)
706 if (!xloadcolor(i, NULL, &dc.col[i])) {
708 die("Could not allocate color '%s'\n", colorname[i]);
710 die("Could not allocate color %d\n", i);
716 xsetcolorname(int x, const char *name)
720 if (!BETWEEN(x, 0, dc.collen))
724 if (!xloadcolor(x, name, &ncolor))
727 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
734 * Absolute coordinates.
737 xclear(int x1, int y1, int x2, int y2)
740 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
741 x1, y1, x2-x1, y2-y1);
747 XClassHint class = {opt_name ? opt_name : termname,
748 opt_class ? opt_class : termname};
749 XWMHints wm = {.flags = InputHint, .input = 1};
750 XSizeHints *sizeh = NULL;
752 sizeh = XAllocSizeHints();
754 sizeh->flags = PSize | PResizeInc | PBaseSize;
755 sizeh->height = win.h;
756 sizeh->width = win.w;
757 sizeh->height_inc = win.ch;
758 sizeh->width_inc = win.cw;
759 sizeh->base_height = 2 * borderpx;
760 sizeh->base_width = 2 * borderpx;
762 sizeh->flags |= PMaxSize | PMinSize;
763 sizeh->min_width = sizeh->max_width = win.w;
764 sizeh->min_height = sizeh->max_height = win.h;
766 if (xw.gm & (XValue|YValue)) {
767 sizeh->flags |= USPosition | PWinGravity;
770 sizeh->win_gravity = xgeommasktogravity(xw.gm);
773 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
779 xgeommasktogravity(int mask)
781 switch (mask & (XNegative|YNegative)) {
783 return NorthWestGravity;
785 return NorthEastGravity;
787 return SouthWestGravity;
790 return SouthEastGravity;
794 xloadfont(Font *f, FcPattern *pattern)
796 FcPattern *configured;
800 int wantattr, haveattr;
803 * Manually configure instead of calling XftMatchFont
804 * so that we can use the configured pattern for
805 * "missing glyph" lookups.
807 configured = FcPatternDuplicate(pattern);
811 FcConfigSubstitute(NULL, configured, FcMatchPattern);
812 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
814 match = FcFontMatch(NULL, configured, &result);
816 FcPatternDestroy(configured);
820 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
821 FcPatternDestroy(configured);
822 FcPatternDestroy(match);
826 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
829 * Check if xft was unable to find a font with the appropriate
830 * slant but gave us one anyway. Try to mitigate.
832 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
833 &haveattr) != XftResultMatch) || haveattr < wantattr) {
835 fputs("st: font slant does not match\n", stderr);
839 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
841 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
842 &haveattr) != XftResultMatch) || haveattr != wantattr) {
844 fputs("st: font weight does not match\n", stderr);
848 XftTextExtentsUtf8(xw.dpy, f->match,
849 (const FcChar8 *) ascii_printable,
850 strlen(ascii_printable), &extents);
853 f->pattern = configured;
855 f->ascent = f->match->ascent;
856 f->descent = f->match->descent;
858 f->rbearing = f->match->max_advance_width;
860 f->height = f->ascent + f->descent;
861 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
867 xloadfonts(char *fontstr, double fontsize)
873 if (fontstr[0] == '-') {
874 pattern = XftXlfdParse(fontstr, False, False);
876 pattern = FcNameParse((FcChar8 *)fontstr);
880 die("st: can't open font %s\n", fontstr);
883 FcPatternDel(pattern, FC_PIXEL_SIZE);
884 FcPatternDel(pattern, FC_SIZE);
885 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
886 usedfontsize = fontsize;
888 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
890 usedfontsize = fontval;
891 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
896 * Default font size is 12, if none given. This is to
897 * have a known usedfontsize value.
899 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
902 defaultfontsize = usedfontsize;
905 if (xloadfont(&dc.font, pattern))
906 die("st: can't open font %s\n", fontstr);
908 if (usedfontsize < 0) {
909 FcPatternGetDouble(dc.font.match->pattern,
910 FC_PIXEL_SIZE, 0, &fontval);
911 usedfontsize = fontval;
913 defaultfontsize = fontval;
916 /* Setting character width and height. */
917 win.cw = ceilf(dc.font.width * cwscale);
918 win.ch = ceilf(dc.font.height * chscale);
920 FcPatternDel(pattern, FC_SLANT);
921 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
922 if (xloadfont(&dc.ifont, pattern))
923 die("st: can't open font %s\n", fontstr);
925 FcPatternDel(pattern, FC_WEIGHT);
926 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
927 if (xloadfont(&dc.ibfont, pattern))
928 die("st: can't open font %s\n", fontstr);
930 FcPatternDel(pattern, FC_SLANT);
931 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
932 if (xloadfont(&dc.bfont, pattern))
933 die("st: can't open font %s\n", fontstr);
935 FcPatternDestroy(pattern);
941 XftFontClose(xw.dpy, f->match);
942 FcPatternDestroy(f->pattern);
944 FcFontSetDestroy(f->set);
950 /* Free the loaded fonts in the font cache. */
952 XftFontClose(xw.dpy, frc[--frclen].font);
954 xunloadfont(&dc.font);
955 xunloadfont(&dc.bfont);
956 xunloadfont(&dc.ifont);
957 xunloadfont(&dc.ibfont);
966 pid_t thispid = getpid();
967 XColor xmousefg, xmousebg;
969 if (!(xw.dpy = XOpenDisplay(NULL)))
970 die("Can't open display\n");
971 xw.scr = XDefaultScreen(xw.dpy);
972 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
976 die("Could not init fontconfig.\n");
978 usedfont = (opt_font == NULL)? font : opt_font;
979 xloadfonts(usedfont, 0);
982 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
985 /* adjust fixed window geometry */
986 win.w = 2 * borderpx + term.col * win.cw;
987 win.h = 2 * borderpx + term.row * win.ch;
988 if (xw.gm & XNegative)
989 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
990 if (xw.gm & YNegative)
991 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
994 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
995 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
996 xw.attrs.bit_gravity = NorthWestGravity;
997 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
998 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
999 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1000 xw.attrs.colormap = xw.cmap;
1002 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1003 parent = XRootWindow(xw.dpy, xw.scr);
1004 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1005 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1006 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1007 | CWEventMask | CWColormap, &xw.attrs);
1009 memset(&gcvalues, 0, sizeof(gcvalues));
1010 gcvalues.graphics_exposures = False;
1011 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1013 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1014 DefaultDepth(xw.dpy, xw.scr));
1015 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1016 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1018 /* font spec buffer */
1019 xw.specbuf = xmalloc(term.col * sizeof(GlyphFontSpec));
1021 /* Xft rendering context */
1022 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1025 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1026 XSetLocaleModifiers("@im=local");
1027 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1028 XSetLocaleModifiers("@im=");
1029 if ((xw.xim = XOpenIM(xw.dpy,
1030 NULL, NULL, NULL)) == NULL) {
1031 die("XOpenIM failed. Could not open input"
1036 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1037 | XIMStatusNothing, XNClientWindow, xw.win,
1038 XNFocusWindow, xw.win, NULL);
1040 die("XCreateIC failed. Could not obtain input method.\n");
1042 /* white cursor, black outline */
1043 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1044 XDefineCursor(xw.dpy, xw.win, cursor);
1046 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1047 xmousefg.red = 0xffff;
1048 xmousefg.green = 0xffff;
1049 xmousefg.blue = 0xffff;
1052 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1053 xmousebg.red = 0x0000;
1054 xmousebg.green = 0x0000;
1055 xmousebg.blue = 0x0000;
1058 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1060 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1061 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1062 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1063 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1065 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1066 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1067 PropModeReplace, (uchar *)&thispid, 1);
1070 XMapWindow(xw.dpy, xw.win);
1072 XSync(xw.dpy, False);
1074 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1075 if (xsel.xtarget == None)
1076 xsel.xtarget = XA_STRING;
1080 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1082 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1083 ushort mode, prevmode = USHRT_MAX;
1084 Font *font = &dc.font;
1085 int frcflags = FRC_NORMAL;
1086 float runewidth = win.cw;
1090 FcPattern *fcpattern, *fontpattern;
1091 FcFontSet *fcsets[] = { NULL };
1092 FcCharSet *fccharset;
1093 int i, f, numspecs = 0;
1095 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1096 /* Fetch rune and mode for current glyph. */
1098 mode = glyphs[i].mode;
1100 /* Skip dummy wide-character spacing. */
1101 if (mode == ATTR_WDUMMY)
1104 /* Determine font for glyph if different from previous glyph. */
1105 if (prevmode != mode) {
1108 frcflags = FRC_NORMAL;
1109 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1110 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1112 frcflags = FRC_ITALICBOLD;
1113 } else if (mode & ATTR_ITALIC) {
1115 frcflags = FRC_ITALIC;
1116 } else if (mode & ATTR_BOLD) {
1118 frcflags = FRC_BOLD;
1120 yp = winy + font->ascent;
1123 /* Lookup character index with default font. */
1124 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1126 specs[numspecs].font = font->match;
1127 specs[numspecs].glyph = glyphidx;
1128 specs[numspecs].x = (short)xp;
1129 specs[numspecs].y = (short)yp;
1135 /* Fallback on font cache, search the font cache for match. */
1136 for (f = 0; f < frclen; f++) {
1137 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1138 /* Everything correct. */
1139 if (glyphidx && frc[f].flags == frcflags)
1141 /* We got a default font for a not found glyph. */
1142 if (!glyphidx && frc[f].flags == frcflags
1143 && frc[f].unicodep == rune) {
1148 /* Nothing was found. Use fontconfig to find matching font. */
1151 font->set = FcFontSort(0, font->pattern,
1153 fcsets[0] = font->set;
1156 * Nothing was found in the cache. Now use
1157 * some dozen of Fontconfig calls to get the
1158 * font for one single character.
1160 * Xft and fontconfig are design failures.
1162 fcpattern = FcPatternDuplicate(font->pattern);
1163 fccharset = FcCharSetCreate();
1165 FcCharSetAddChar(fccharset, rune);
1166 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1168 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1170 FcConfigSubstitute(0, fcpattern,
1172 FcDefaultSubstitute(fcpattern);
1174 fontpattern = FcFontSetMatch(0, fcsets, 1,
1178 * Overwrite or create the new cache entry.
1180 if (frclen >= LEN(frc)) {
1181 frclen = LEN(frc) - 1;
1182 XftFontClose(xw.dpy, frc[frclen].font);
1183 frc[frclen].unicodep = 0;
1186 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1188 if (!frc[frclen].font)
1189 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1191 frc[frclen].flags = frcflags;
1192 frc[frclen].unicodep = rune;
1194 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1199 FcPatternDestroy(fcpattern);
1200 FcCharSetDestroy(fccharset);
1203 specs[numspecs].font = frc[f].font;
1204 specs[numspecs].glyph = glyphidx;
1205 specs[numspecs].x = (short)xp;
1206 specs[numspecs].y = (short)yp;
1215 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1217 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1218 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1219 width = charlen * win.cw;
1220 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1221 XRenderColor colfg, colbg;
1224 /* Fallback on color display for attributes not supported by the font */
1225 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1226 if (dc.ibfont.badslant || dc.ibfont.badweight)
1227 base.fg = defaultattr;
1228 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1229 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1230 base.fg = defaultattr;
1233 if (IS_TRUECOL(base.fg)) {
1234 colfg.alpha = 0xffff;
1235 colfg.red = TRUERED(base.fg);
1236 colfg.green = TRUEGREEN(base.fg);
1237 colfg.blue = TRUEBLUE(base.fg);
1238 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1241 fg = &dc.col[base.fg];
1244 if (IS_TRUECOL(base.bg)) {
1245 colbg.alpha = 0xffff;
1246 colbg.green = TRUEGREEN(base.bg);
1247 colbg.red = TRUERED(base.bg);
1248 colbg.blue = TRUEBLUE(base.bg);
1249 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1252 bg = &dc.col[base.bg];
1255 /* Change basic system colors [0-7] to bright system colors [8-15] */
1256 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1257 fg = &dc.col[base.fg + 8];
1259 if (IS_SET(MODE_REVERSE)) {
1260 if (fg == &dc.col[defaultfg]) {
1261 fg = &dc.col[defaultbg];
1263 colfg.red = ~fg->color.red;
1264 colfg.green = ~fg->color.green;
1265 colfg.blue = ~fg->color.blue;
1266 colfg.alpha = fg->color.alpha;
1267 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1272 if (bg == &dc.col[defaultbg]) {
1273 bg = &dc.col[defaultfg];
1275 colbg.red = ~bg->color.red;
1276 colbg.green = ~bg->color.green;
1277 colbg.blue = ~bg->color.blue;
1278 colbg.alpha = bg->color.alpha;
1279 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1285 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1286 colfg.red = fg->color.red / 2;
1287 colfg.green = fg->color.green / 2;
1288 colfg.blue = fg->color.blue / 2;
1289 colfg.alpha = fg->color.alpha;
1290 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1295 if (base.mode & ATTR_REVERSE) {
1301 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1304 if (base.mode & ATTR_INVISIBLE)
1307 /* Intelligent cleaning up of the borders. */
1309 xclear(0, (y == 0)? 0 : winy, borderpx,
1310 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1312 if (x + charlen >= term.col) {
1313 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1314 ((y >= term.row-1)? win.h : (winy + win.ch)));
1317 xclear(winx, 0, winx + width, borderpx);
1318 if (y == term.row-1)
1319 xclear(winx, winy + win.ch, winx + width, win.h);
1321 /* Clean up the region we want to draw to. */
1322 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1324 /* Set the clip region because Xft is sometimes dirty. */
1329 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1331 /* Render the glyphs. */
1332 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1334 /* Render underline and strikethrough. */
1335 if (base.mode & ATTR_UNDERLINE) {
1336 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1340 if (base.mode & ATTR_STRUCK) {
1341 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1345 /* Reset clip to none. */
1346 XftDrawSetClip(xw.draw, 0);
1350 xdrawglyph(Glyph g, int x, int y)
1353 XftGlyphFontSpec spec;
1355 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1356 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1362 static int oldx = 0, oldy = 0;
1364 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1365 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1368 LIMIT(oldx, 0, term.col-1);
1369 LIMIT(oldy, 0, term.row-1);
1373 /* adjust position if in dummy */
1374 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1376 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1379 /* remove the old cursor */
1380 og = term.line[oldy][oldx];
1381 if (ena_sel && selected(oldx, oldy))
1382 og.mode ^= ATTR_REVERSE;
1383 xdrawglyph(og, oldx, oldy);
1385 g.u = term.line[term.c.y][term.c.x].u;
1386 g.mode |= term.line[term.c.y][term.c.x].mode &
1387 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1390 * Select the right color for the right mode.
1392 if (IS_SET(MODE_REVERSE)) {
1393 g.mode |= ATTR_REVERSE;
1395 if (ena_sel && selected(term.c.x, term.c.y)) {
1396 drawcol = dc.col[defaultcs];
1399 drawcol = dc.col[defaultrcs];
1403 if (ena_sel && selected(term.c.x, term.c.y)) {
1404 drawcol = dc.col[defaultrcs];
1408 drawcol = dc.col[defaultcs];
1412 if (IS_SET(MODE_HIDE))
1415 /* draw the new one */
1416 if (win.state & WIN_FOCUSED) {
1417 switch (win.cursor) {
1418 case 7: /* st extension: snowman */
1419 utf8decode("☃", &g.u, UTF_SIZ);
1420 case 0: /* Blinking Block */
1421 case 1: /* Blinking Block (Default) */
1422 case 2: /* Steady Block */
1423 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1424 xdrawglyph(g, term.c.x, term.c.y);
1426 case 3: /* Blinking Underline */
1427 case 4: /* Steady Underline */
1428 XftDrawRect(xw.draw, &drawcol,
1429 borderpx + curx * win.cw,
1430 borderpx + (term.c.y + 1) * win.ch - \
1432 win.cw, cursorthickness);
1434 case 5: /* Blinking bar */
1435 case 6: /* Steady bar */
1436 XftDrawRect(xw.draw, &drawcol,
1437 borderpx + curx * win.cw,
1438 borderpx + term.c.y * win.ch,
1439 cursorthickness, win.ch);
1443 XftDrawRect(xw.draw, &drawcol,
1444 borderpx + curx * win.cw,
1445 borderpx + term.c.y * win.ch,
1447 XftDrawRect(xw.draw, &drawcol,
1448 borderpx + curx * win.cw,
1449 borderpx + term.c.y * win.ch,
1451 XftDrawRect(xw.draw, &drawcol,
1452 borderpx + (curx + 1) * win.cw - 1,
1453 borderpx + term.c.y * win.ch,
1455 XftDrawRect(xw.draw, &drawcol,
1456 borderpx + curx * win.cw,
1457 borderpx + (term.c.y + 1) * win.ch - 1,
1460 oldx = curx, oldy = term.c.y;
1466 char buf[sizeof(long) * 8 + 1];
1468 snprintf(buf, sizeof(buf), "%lu", xw.win);
1469 setenv("WINDOWID", buf, 1);
1477 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1479 XSetWMName(xw.dpy, xw.win, &prop);
1480 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1487 drawregion(0, 0, term.col, term.row);
1488 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1490 XSetForeground(xw.dpy, dc.gc,
1491 dc.col[IS_SET(MODE_REVERSE)?
1492 defaultfg : defaultbg].pixel);
1496 drawregion(int x1, int y1, int x2, int y2)
1498 int i, x, y, ox, numspecs;
1500 XftGlyphFontSpec *specs;
1501 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1503 if (!(win.state & WIN_VISIBLE))
1506 for (y = y1; y < y2; y++) {
1513 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1516 for (x = x1; x < x2 && i < numspecs; x++) {
1517 new = term.line[y][x];
1518 if (new.mode == ATTR_WDUMMY)
1520 if (ena_sel && selected(x, y))
1521 new.mode ^= ATTR_REVERSE;
1522 if (i > 0 && ATTRCMP(base, new)) {
1523 xdrawglyphfontspecs(specs, base, i, ox, y);
1535 xdrawglyphfontspecs(specs, base, i, ox, y);
1547 visibility(XEvent *ev)
1549 XVisibilityEvent *e = &ev->xvisibility;
1551 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1557 win.state &= ~WIN_VISIBLE;
1561 xsetpointermotion(int set)
1563 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1564 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1568 xseturgency(int add)
1570 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1572 MODBIT(h->flags, add, XUrgencyHint);
1573 XSetWMHints(xw.dpy, xw.win, h);
1580 if (!(win.state & WIN_FOCUSED))
1583 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1589 XFocusChangeEvent *e = &ev->xfocus;
1591 if (e->mode == NotifyGrab)
1594 if (ev->type == FocusIn) {
1595 XSetICFocus(xw.xic);
1596 win.state |= WIN_FOCUSED;
1598 if (IS_SET(MODE_FOCUS))
1599 ttywrite("\033[I", 3);
1601 XUnsetICFocus(xw.xic);
1602 win.state &= ~WIN_FOCUSED;
1603 if (IS_SET(MODE_FOCUS))
1604 ttywrite("\033[O", 3);
1609 match(uint mask, uint state)
1611 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1615 kmap(KeySym k, uint state)
1620 /* Check for mapped keys out of X11 function keys. */
1621 for (i = 0; i < mappedkeyslen; i++) {
1622 if (mappedkeys[i] == k)
1625 if (i == mappedkeyslen) {
1626 if ((k & 0xFFFF) < 0xFD00)
1630 for (kp = key; kp < key + keyslen; kp++) {
1634 if (!match(kp->mask, state))
1637 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1639 if (term.numlock && kp->appkey == 2)
1642 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1645 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
1657 XKeyEvent *e = &ev->xkey;
1659 char buf[32], *customkey;
1665 if (IS_SET(MODE_KBDLOCK))
1668 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1670 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1671 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1672 bp->func(&(bp->arg));
1677 /* 2. custom keys from config.h */
1678 if ((customkey = kmap(ksym, e->state))) {
1679 ttysend(customkey, strlen(customkey));
1683 /* 3. composed string from input method */
1686 if (len == 1 && e->state & Mod1Mask) {
1687 if (IS_SET(MODE_8BIT)) {
1690 len = utf8encode(c, buf);
1707 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1709 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1710 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1711 win.state |= WIN_FOCUSED;
1713 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1714 win.state &= ~WIN_FOCUSED;
1716 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1717 /* Send SIGHUP to shell */
1726 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1729 cresize(e->xconfigure.width, e->xconfigure.height);
1730 ttyresize(win.tw, win.th);
1737 int w = win.w, h = win.h;
1739 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1740 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1743 /* Waiting for window mapping */
1745 XNextEvent(xw.dpy, &ev);
1747 * This XFilterEvent call is required because of XOpenIM. It
1748 * does filter out the key event and some client message for
1749 * the input method too.
1751 if (XFilterEvent(&ev, None))
1753 if (ev.type == ConfigureNotify) {
1754 w = ev.xconfigure.width;
1755 h = ev.xconfigure.height;
1757 } while (ev.type != MapNotify);
1761 ttyresize(win.tw, win.th);
1763 clock_gettime(CLOCK_MONOTONIC, &last);
1766 for (xev = actionfps;;) {
1768 FD_SET(cmdfd, &rfd);
1771 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1774 die("select failed: %s\n", strerror(errno));
1776 if (FD_ISSET(cmdfd, &rfd)) {
1779 blinkset = tattrset(ATTR_BLINK);
1781 MODBIT(term.mode, 0, MODE_BLINK);
1785 if (FD_ISSET(xfd, &rfd))
1788 clock_gettime(CLOCK_MONOTONIC, &now);
1789 drawtimeout.tv_sec = 0;
1790 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1794 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1795 tsetdirtattr(ATTR_BLINK);
1796 term.mode ^= MODE_BLINK;
1800 deltatime = TIMEDIFF(now, last);
1801 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1807 while (XPending(xw.dpy)) {
1808 XNextEvent(xw.dpy, &ev);
1809 if (XFilterEvent(&ev, None))
1811 if (handler[ev.type])
1812 (handler[ev.type])(&ev);
1818 if (xev && !FD_ISSET(xfd, &rfd))
1820 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1822 if (TIMEDIFF(now, lastblink) \
1824 drawtimeout.tv_nsec = 1000;
1826 drawtimeout.tv_nsec = (1E6 * \
1831 drawtimeout.tv_sec = \
1832 drawtimeout.tv_nsec / 1E9;
1833 drawtimeout.tv_nsec %= (long)1E9;
1845 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1846 " [-n name] [-o file]\n"
1847 " [-T title] [-t title] [-w windowid]"
1848 " [[-e] command [args ...]]\n"
1849 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1850 " [-n name] [-o file]\n"
1851 " [-T title] [-t title] [-w windowid] -l line"
1852 " [stty_args ...]\n", argv0, argv0);
1856 main(int argc, char *argv[])
1860 win.cursor = cursorshape;
1867 opt_class = EARGF(usage());
1874 opt_font = EARGF(usage());
1877 xw.gm = XParseGeometry(EARGF(usage()),
1878 &xw.l, &xw.t, &cols, &rows);
1884 opt_io = EARGF(usage());
1887 opt_line = EARGF(usage());
1890 opt_name = EARGF(usage());
1894 opt_title = EARGF(usage());
1897 opt_embed = EARGF(usage());
1900 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1908 /* eat all remaining arguments */
1910 if (!opt_title && !opt_line)
1911 opt_title = basename(xstrdup(argv[0]));
1913 setlocale(LC_CTYPE, "");
1914 XSetLocaleModifiers("");
1915 tnew(MAX(cols, 1), MAX(rows, 1));