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 *);
120 static void run(void);
121 static void usage(void);
123 static void (*handler[LASTEvent])(XEvent *) = {
125 [ClientMessage] = cmessage,
126 [ConfigureNotify] = resize,
127 [VisibilityNotify] = visibility,
128 [UnmapNotify] = unmap,
132 [MotionNotify] = bmotion,
133 [ButtonPress] = bpress,
134 [ButtonRelease] = brelease,
136 * Uncomment if you want the selection to disappear when you select something
137 * different in another window.
139 /* [SelectionClear] = selclear_, */
140 [SelectionNotify] = selnotify,
142 * PropertyNotify is only turned on when there is some INCR transfer happening
143 * for the selection retrieval.
145 [PropertyNotify] = propnotify,
146 [SelectionRequest] = selrequest,
152 static XSelection xsel;
159 /* Font Ring Cache */
173 /* Fontcache is an array now. A new font will be appended to the array. */
174 static Fontcache frc[16];
175 static int frclen = 0;
176 static char *usedfont = NULL;
177 static double usedfontsize = 0;
178 static double defaultfontsize = 0;
185 larg.f = usedfontsize + arg->f;
190 zoomabs(const Arg *arg)
193 xloadfonts(usedfont, arg->f);
195 ttyresize(win.tw, win.th);
201 zoomreset(const Arg *arg)
205 if (defaultfontsize > 0) {
206 larg.f = defaultfontsize;
217 return LIMIT(x, 0, term.col-1);
226 return LIMIT(y, 0, term.row-1);
230 getbuttoninfo(XEvent *e)
233 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
235 sel.alt = IS_SET(MODE_ALTSCREEN);
237 sel.oe.x = x2col(e->xbutton.x);
238 sel.oe.y = y2row(e->xbutton.y);
241 sel.type = SEL_REGULAR;
242 for (type = 1; type < selmaskslen; ++type) {
243 if (match(selmasks[type], state)) {
251 mousereport(XEvent *e)
253 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
254 button = e->xbutton.button, state = e->xbutton.state,
260 if (e->xbutton.type == MotionNotify) {
261 if (x == ox && y == oy)
263 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
265 /* MOUSE_MOTION: no reporting if no button is pressed */
266 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
269 button = oldbutton + 32;
273 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
280 if (e->xbutton.type == ButtonPress) {
284 } else if (e->xbutton.type == ButtonRelease) {
286 /* MODE_MOUSEX10: no button release reporting */
287 if (IS_SET(MODE_MOUSEX10))
289 if (button == 64 || button == 65)
294 if (!IS_SET(MODE_MOUSEX10)) {
295 button += ((state & ShiftMask ) ? 4 : 0)
296 + ((state & Mod4Mask ) ? 8 : 0)
297 + ((state & ControlMask) ? 16 : 0);
300 if (IS_SET(MODE_MOUSESGR)) {
301 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
303 e->xbutton.type == ButtonRelease ? 'm' : 'M');
304 } else if (x < 223 && y < 223) {
305 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
306 32+button, 32+x+1, 32+y+1);
320 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
325 for (ms = mshortcuts; ms < mshortcuts + mshortcutslen; ms++) {
326 if (e->xbutton.button == ms->b
327 && match(ms->mask, e->xbutton.state)) {
328 ttysend(ms->s, strlen(ms->s));
333 if (e->xbutton.button == Button1) {
334 clock_gettime(CLOCK_MONOTONIC, &now);
336 /* Clear previous selection, logically and visually. */
338 sel.mode = SEL_EMPTY;
339 sel.type = SEL_REGULAR;
340 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
341 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
344 * If the user clicks below predefined timeouts specific
345 * snapping behaviour is exposed.
347 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
348 sel.snap = SNAP_LINE;
349 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
350 sel.snap = SNAP_WORD;
357 sel.mode = SEL_READY;
358 tsetdirt(sel.nb.y, sel.ne.y);
359 sel.tclick2 = sel.tclick1;
367 xsetsel(getsel(), t);
371 propnotify(XEvent *e)
373 XPropertyEvent *xpev;
374 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
376 xpev = &e->xproperty;
377 if (xpev->state == PropertyNewValue &&
378 (xpev->atom == XA_PRIMARY ||
379 xpev->atom == clipboard)) {
387 ulong nitems, ofs, rem;
389 uchar *data, *last, *repl;
390 Atom type, incratom, property;
392 incratom = XInternAtom(xw.dpy, "INCR", 0);
395 if (e->type == SelectionNotify) {
396 property = e->xselection.property;
397 } else if(e->type == PropertyNotify) {
398 property = e->xproperty.atom;
402 if (property == None)
406 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
407 BUFSIZ/4, False, AnyPropertyType,
408 &type, &format, &nitems, &rem,
410 fprintf(stderr, "Clipboard allocation failed\n");
414 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
416 * If there is some PropertyNotify with no data, then
417 * this is the signal of the selection owner that all
418 * data has been transferred. We won't need to receive
419 * PropertyNotify events anymore.
421 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
422 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
426 if (type == incratom) {
428 * Activate the PropertyNotify events so we receive
429 * when the selection owner does send us the next
432 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
433 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
437 * Deleting the property is the transfer start signal.
439 XDeleteProperty(xw.dpy, xw.win, (int)property);
445 * Line endings are inconsistent in the terminal and GUI world
446 * copy and pasting. When receiving some selection data,
447 * replace all '\n' with '\r'.
448 * FIXME: Fix the computer world.
451 last = data + nitems * format / 8;
452 while ((repl = memchr(repl, '\n', last - repl))) {
456 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
457 ttywrite("\033[200~", 6);
458 ttysend((char *)data, nitems * format / 8);
459 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
460 ttywrite("\033[201~", 6);
462 /* number of 32-bit chunks returned */
463 ofs += nitems * format / 32;
467 * Deleting the property again tells the selection owner to send the
468 * next data chunk in the property.
470 XDeleteProperty(xw.dpy, xw.win, (int)property);
476 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
477 xw.win, CurrentTime);
485 if (sel.clipboard != NULL)
488 if (sel.primary != NULL) {
489 sel.clipboard = xstrdup(sel.primary);
490 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
491 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
500 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
501 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
502 xw.win, CurrentTime);
512 selrequest(XEvent *e)
514 XSelectionRequestEvent *xsre;
516 Atom xa_targets, string, clipboard;
519 xsre = (XSelectionRequestEvent *) e;
520 xev.type = SelectionNotify;
521 xev.requestor = xsre->requestor;
522 xev.selection = xsre->selection;
523 xev.target = xsre->target;
524 xev.time = xsre->time;
525 if (xsre->property == None)
526 xsre->property = xsre->target;
531 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
532 if (xsre->target == xa_targets) {
533 /* respond with the supported type */
534 string = xsel.xtarget;
535 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
536 XA_ATOM, 32, PropModeReplace,
537 (uchar *) &string, 1);
538 xev.property = xsre->property;
539 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
541 * xith XA_STRING non ascii characters may be incorrect in the
542 * requestor. It is not our problem, use utf8.
544 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
545 if (xsre->selection == XA_PRIMARY) {
546 seltext = sel.primary;
547 } else if (xsre->selection == clipboard) {
548 seltext = sel.clipboard;
551 "Unhandled clipboard selection 0x%lx\n",
555 if (seltext != NULL) {
556 XChangeProperty(xsre->display, xsre->requestor,
557 xsre->property, xsre->target,
559 (uchar *)seltext, strlen(seltext));
560 xev.property = xsre->property;
564 /* all done, send a notification to the listener */
565 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
566 fprintf(stderr, "Error sending SelectionNotify event\n");
570 xsetsel(char *str, Time t)
575 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
576 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
583 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
588 if (e->xbutton.button == Button2) {
590 } else if (e->xbutton.button == Button1) {
591 if (sel.mode == SEL_READY) {
593 selcopy(e->xbutton.time);
597 tsetdirt(sel.nb.y, sel.ne.y);
604 int oldey, oldex, oldsby, oldsey;
606 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
614 sel.mode = SEL_READY;
621 if (oldey != sel.oe.y || oldex != sel.oe.x)
622 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
626 cresize(int width, int height)
635 col = (win.w - 2 * borderpx) / win.cw;
636 row = (win.h - 2 * borderpx) / win.ch;
643 xresize(int col, int row)
645 win.tw = MAX(1, col * win.cw);
646 win.th = MAX(1, row * win.ch);
648 XFreePixmap(xw.dpy, xw.buf);
649 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
650 DefaultDepth(xw.dpy, xw.scr));
651 XftDrawChange(xw.draw, xw.buf);
652 xclear(0, 0, win.w, win.h);
654 /* resize to new width */
655 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
661 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
665 xloadcolor(int i, const char *name, Color *ncolor)
667 XRenderColor color = { .alpha = 0xffff };
670 if (BETWEEN(i, 16, 255)) { /* 256 color */
671 if (i < 6*6*6+16) { /* same colors as xterm */
672 color.red = sixd_to_16bit( ((i-16)/36)%6 );
673 color.green = sixd_to_16bit( ((i-16)/6) %6 );
674 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
675 } else { /* greyscale */
676 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
677 color.green = color.blue = color.red;
679 return XftColorAllocValue(xw.dpy, xw.vis,
680 xw.cmap, &color, ncolor);
685 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
695 dc.collen = MAX(colornamelen, 256);
696 dc.col = xmalloc(dc.collen * sizeof(Color));
699 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
700 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
703 for (i = 0; i < dc.collen; i++)
704 if (!xloadcolor(i, NULL, &dc.col[i])) {
706 die("Could not allocate color '%s'\n", colorname[i]);
708 die("Could not allocate color %d\n", i);
714 xsetcolorname(int x, const char *name)
718 if (!BETWEEN(x, 0, dc.collen))
722 if (!xloadcolor(x, name, &ncolor))
725 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
732 * Absolute coordinates.
735 xclear(int x1, int y1, int x2, int y2)
738 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
739 x1, y1, x2-x1, y2-y1);
745 XClassHint class = {opt_name ? opt_name : termname,
746 opt_class ? opt_class : termname};
747 XWMHints wm = {.flags = InputHint, .input = 1};
748 XSizeHints *sizeh = NULL;
750 sizeh = XAllocSizeHints();
752 sizeh->flags = PSize | PResizeInc | PBaseSize;
753 sizeh->height = win.h;
754 sizeh->width = win.w;
755 sizeh->height_inc = win.ch;
756 sizeh->width_inc = win.cw;
757 sizeh->base_height = 2 * borderpx;
758 sizeh->base_width = 2 * borderpx;
760 sizeh->flags |= PMaxSize | PMinSize;
761 sizeh->min_width = sizeh->max_width = win.w;
762 sizeh->min_height = sizeh->max_height = win.h;
764 if (xw.gm & (XValue|YValue)) {
765 sizeh->flags |= USPosition | PWinGravity;
768 sizeh->win_gravity = xgeommasktogravity(xw.gm);
771 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
777 xgeommasktogravity(int mask)
779 switch (mask & (XNegative|YNegative)) {
781 return NorthWestGravity;
783 return NorthEastGravity;
785 return SouthWestGravity;
788 return SouthEastGravity;
792 xloadfont(Font *f, FcPattern *pattern)
794 FcPattern *configured;
798 int wantattr, haveattr;
801 * Manually configure instead of calling XftMatchFont
802 * so that we can use the configured pattern for
803 * "missing glyph" lookups.
805 configured = FcPatternDuplicate(pattern);
809 FcConfigSubstitute(NULL, configured, FcMatchPattern);
810 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
812 match = FcFontMatch(NULL, configured, &result);
814 FcPatternDestroy(configured);
818 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
819 FcPatternDestroy(configured);
820 FcPatternDestroy(match);
824 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
827 * Check if xft was unable to find a font with the appropriate
828 * slant but gave us one anyway. Try to mitigate.
830 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
831 &haveattr) != XftResultMatch) || haveattr < wantattr) {
833 fputs("st: font slant does not match\n", stderr);
837 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
839 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
840 &haveattr) != XftResultMatch) || haveattr != wantattr) {
842 fputs("st: font weight does not match\n", stderr);
846 XftTextExtentsUtf8(xw.dpy, f->match,
847 (const FcChar8 *) ascii_printable,
848 strlen(ascii_printable), &extents);
851 f->pattern = configured;
853 f->ascent = f->match->ascent;
854 f->descent = f->match->descent;
856 f->rbearing = f->match->max_advance_width;
858 f->height = f->ascent + f->descent;
859 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
865 xloadfonts(char *fontstr, double fontsize)
871 if (fontstr[0] == '-') {
872 pattern = XftXlfdParse(fontstr, False, False);
874 pattern = FcNameParse((FcChar8 *)fontstr);
878 die("st: can't open font %s\n", fontstr);
881 FcPatternDel(pattern, FC_PIXEL_SIZE);
882 FcPatternDel(pattern, FC_SIZE);
883 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
884 usedfontsize = fontsize;
886 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
888 usedfontsize = fontval;
889 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
894 * Default font size is 12, if none given. This is to
895 * have a known usedfontsize value.
897 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
900 defaultfontsize = usedfontsize;
903 if (xloadfont(&dc.font, pattern))
904 die("st: can't open font %s\n", fontstr);
906 if (usedfontsize < 0) {
907 FcPatternGetDouble(dc.font.match->pattern,
908 FC_PIXEL_SIZE, 0, &fontval);
909 usedfontsize = fontval;
911 defaultfontsize = fontval;
914 /* Setting character width and height. */
915 win.cw = ceilf(dc.font.width * cwscale);
916 win.ch = ceilf(dc.font.height * chscale);
918 FcPatternDel(pattern, FC_SLANT);
919 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
920 if (xloadfont(&dc.ifont, pattern))
921 die("st: can't open font %s\n", fontstr);
923 FcPatternDel(pattern, FC_WEIGHT);
924 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
925 if (xloadfont(&dc.ibfont, pattern))
926 die("st: can't open font %s\n", fontstr);
928 FcPatternDel(pattern, FC_SLANT);
929 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
930 if (xloadfont(&dc.bfont, pattern))
931 die("st: can't open font %s\n", fontstr);
933 FcPatternDestroy(pattern);
939 XftFontClose(xw.dpy, f->match);
940 FcPatternDestroy(f->pattern);
942 FcFontSetDestroy(f->set);
948 /* Free the loaded fonts in the font cache. */
950 XftFontClose(xw.dpy, frc[--frclen].font);
952 xunloadfont(&dc.font);
953 xunloadfont(&dc.bfont);
954 xunloadfont(&dc.ifont);
955 xunloadfont(&dc.ibfont);
964 pid_t thispid = getpid();
965 XColor xmousefg, xmousebg;
967 if (!(xw.dpy = XOpenDisplay(NULL)))
968 die("Can't open display\n");
969 xw.scr = XDefaultScreen(xw.dpy);
970 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
974 die("Could not init fontconfig.\n");
976 usedfont = (opt_font == NULL)? font : opt_font;
977 xloadfonts(usedfont, 0);
980 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
983 /* adjust fixed window geometry */
984 win.w = 2 * borderpx + term.col * win.cw;
985 win.h = 2 * borderpx + term.row * win.ch;
986 if (xw.gm & XNegative)
987 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
988 if (xw.gm & YNegative)
989 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
992 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
993 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
994 xw.attrs.bit_gravity = NorthWestGravity;
995 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
996 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
997 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
998 xw.attrs.colormap = xw.cmap;
1000 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1001 parent = XRootWindow(xw.dpy, xw.scr);
1002 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1003 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1004 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1005 | CWEventMask | CWColormap, &xw.attrs);
1007 memset(&gcvalues, 0, sizeof(gcvalues));
1008 gcvalues.graphics_exposures = False;
1009 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1011 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1012 DefaultDepth(xw.dpy, xw.scr));
1013 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1014 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1016 /* font spec buffer */
1017 xw.specbuf = xmalloc(term.col * sizeof(GlyphFontSpec));
1019 /* Xft rendering context */
1020 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1023 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1024 XSetLocaleModifiers("@im=local");
1025 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1026 XSetLocaleModifiers("@im=");
1027 if ((xw.xim = XOpenIM(xw.dpy,
1028 NULL, NULL, NULL)) == NULL) {
1029 die("XOpenIM failed. Could not open input"
1034 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1035 | XIMStatusNothing, XNClientWindow, xw.win,
1036 XNFocusWindow, xw.win, NULL);
1038 die("XCreateIC failed. Could not obtain input method.\n");
1040 /* white cursor, black outline */
1041 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1042 XDefineCursor(xw.dpy, xw.win, cursor);
1044 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1045 xmousefg.red = 0xffff;
1046 xmousefg.green = 0xffff;
1047 xmousefg.blue = 0xffff;
1050 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1051 xmousebg.red = 0x0000;
1052 xmousebg.green = 0x0000;
1053 xmousebg.blue = 0x0000;
1056 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1058 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1059 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1060 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1061 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1063 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1064 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1065 PropModeReplace, (uchar *)&thispid, 1);
1068 XMapWindow(xw.dpy, xw.win);
1070 XSync(xw.dpy, False);
1072 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1073 if (xsel.xtarget == None)
1074 xsel.xtarget = XA_STRING;
1078 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1080 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1081 ushort mode, prevmode = USHRT_MAX;
1082 Font *font = &dc.font;
1083 int frcflags = FRC_NORMAL;
1084 float runewidth = win.cw;
1088 FcPattern *fcpattern, *fontpattern;
1089 FcFontSet *fcsets[] = { NULL };
1090 FcCharSet *fccharset;
1091 int i, f, numspecs = 0;
1093 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1094 /* Fetch rune and mode for current glyph. */
1096 mode = glyphs[i].mode;
1098 /* Skip dummy wide-character spacing. */
1099 if (mode == ATTR_WDUMMY)
1102 /* Determine font for glyph if different from previous glyph. */
1103 if (prevmode != mode) {
1106 frcflags = FRC_NORMAL;
1107 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1108 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1110 frcflags = FRC_ITALICBOLD;
1111 } else if (mode & ATTR_ITALIC) {
1113 frcflags = FRC_ITALIC;
1114 } else if (mode & ATTR_BOLD) {
1116 frcflags = FRC_BOLD;
1118 yp = winy + font->ascent;
1121 /* Lookup character index with default font. */
1122 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1124 specs[numspecs].font = font->match;
1125 specs[numspecs].glyph = glyphidx;
1126 specs[numspecs].x = (short)xp;
1127 specs[numspecs].y = (short)yp;
1133 /* Fallback on font cache, search the font cache for match. */
1134 for (f = 0; f < frclen; f++) {
1135 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1136 /* Everything correct. */
1137 if (glyphidx && frc[f].flags == frcflags)
1139 /* We got a default font for a not found glyph. */
1140 if (!glyphidx && frc[f].flags == frcflags
1141 && frc[f].unicodep == rune) {
1146 /* Nothing was found. Use fontconfig to find matching font. */
1149 font->set = FcFontSort(0, font->pattern,
1151 fcsets[0] = font->set;
1154 * Nothing was found in the cache. Now use
1155 * some dozen of Fontconfig calls to get the
1156 * font for one single character.
1158 * Xft and fontconfig are design failures.
1160 fcpattern = FcPatternDuplicate(font->pattern);
1161 fccharset = FcCharSetCreate();
1163 FcCharSetAddChar(fccharset, rune);
1164 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1166 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1168 FcConfigSubstitute(0, fcpattern,
1170 FcDefaultSubstitute(fcpattern);
1172 fontpattern = FcFontSetMatch(0, fcsets, 1,
1176 * Overwrite or create the new cache entry.
1178 if (frclen >= LEN(frc)) {
1179 frclen = LEN(frc) - 1;
1180 XftFontClose(xw.dpy, frc[frclen].font);
1181 frc[frclen].unicodep = 0;
1184 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1186 if (!frc[frclen].font)
1187 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1189 frc[frclen].flags = frcflags;
1190 frc[frclen].unicodep = rune;
1192 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1197 FcPatternDestroy(fcpattern);
1198 FcCharSetDestroy(fccharset);
1201 specs[numspecs].font = frc[f].font;
1202 specs[numspecs].glyph = glyphidx;
1203 specs[numspecs].x = (short)xp;
1204 specs[numspecs].y = (short)yp;
1213 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1215 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1216 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1217 width = charlen * win.cw;
1218 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1219 XRenderColor colfg, colbg;
1222 /* Fallback on color display for attributes not supported by the font */
1223 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1224 if (dc.ibfont.badslant || dc.ibfont.badweight)
1225 base.fg = defaultattr;
1226 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1227 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1228 base.fg = defaultattr;
1231 if (IS_TRUECOL(base.fg)) {
1232 colfg.alpha = 0xffff;
1233 colfg.red = TRUERED(base.fg);
1234 colfg.green = TRUEGREEN(base.fg);
1235 colfg.blue = TRUEBLUE(base.fg);
1236 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1239 fg = &dc.col[base.fg];
1242 if (IS_TRUECOL(base.bg)) {
1243 colbg.alpha = 0xffff;
1244 colbg.green = TRUEGREEN(base.bg);
1245 colbg.red = TRUERED(base.bg);
1246 colbg.blue = TRUEBLUE(base.bg);
1247 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1250 bg = &dc.col[base.bg];
1253 /* Change basic system colors [0-7] to bright system colors [8-15] */
1254 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1255 fg = &dc.col[base.fg + 8];
1257 if (IS_SET(MODE_REVERSE)) {
1258 if (fg == &dc.col[defaultfg]) {
1259 fg = &dc.col[defaultbg];
1261 colfg.red = ~fg->color.red;
1262 colfg.green = ~fg->color.green;
1263 colfg.blue = ~fg->color.blue;
1264 colfg.alpha = fg->color.alpha;
1265 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1270 if (bg == &dc.col[defaultbg]) {
1271 bg = &dc.col[defaultfg];
1273 colbg.red = ~bg->color.red;
1274 colbg.green = ~bg->color.green;
1275 colbg.blue = ~bg->color.blue;
1276 colbg.alpha = bg->color.alpha;
1277 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1283 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1284 colfg.red = fg->color.red / 2;
1285 colfg.green = fg->color.green / 2;
1286 colfg.blue = fg->color.blue / 2;
1287 colfg.alpha = fg->color.alpha;
1288 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1293 if (base.mode & ATTR_REVERSE) {
1299 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
1302 if (base.mode & ATTR_INVISIBLE)
1305 /* Intelligent cleaning up of the borders. */
1307 xclear(0, (y == 0)? 0 : winy, borderpx,
1308 winy + win.ch + ((y >= term.row-1)? win.h : 0));
1310 if (x + charlen >= term.col) {
1311 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1312 ((y >= term.row-1)? win.h : (winy + win.ch)));
1315 xclear(winx, 0, winx + width, borderpx);
1316 if (y == term.row-1)
1317 xclear(winx, winy + win.ch, winx + width, win.h);
1319 /* Clean up the region we want to draw to. */
1320 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1322 /* Set the clip region because Xft is sometimes dirty. */
1327 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1329 /* Render the glyphs. */
1330 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1332 /* Render underline and strikethrough. */
1333 if (base.mode & ATTR_UNDERLINE) {
1334 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1338 if (base.mode & ATTR_STRUCK) {
1339 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1343 /* Reset clip to none. */
1344 XftDrawSetClip(xw.draw, 0);
1348 xdrawglyph(Glyph g, int x, int y)
1351 XftGlyphFontSpec spec;
1353 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1354 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1360 static int oldx = 0, oldy = 0;
1362 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
1363 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1366 LIMIT(oldx, 0, term.col-1);
1367 LIMIT(oldy, 0, term.row-1);
1371 /* adjust position if in dummy */
1372 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
1374 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
1377 /* remove the old cursor */
1378 og = term.line[oldy][oldx];
1379 if (ena_sel && selected(oldx, oldy))
1380 og.mode ^= ATTR_REVERSE;
1381 xdrawglyph(og, oldx, oldy);
1383 g.u = term.line[term.c.y][term.c.x].u;
1384 g.mode |= term.line[term.c.y][term.c.x].mode &
1385 (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
1388 * Select the right color for the right mode.
1390 if (IS_SET(MODE_REVERSE)) {
1391 g.mode |= ATTR_REVERSE;
1393 if (ena_sel && selected(term.c.x, term.c.y)) {
1394 drawcol = dc.col[defaultcs];
1397 drawcol = dc.col[defaultrcs];
1401 if (ena_sel && selected(term.c.x, term.c.y)) {
1402 drawcol = dc.col[defaultrcs];
1406 drawcol = dc.col[defaultcs];
1410 if (IS_SET(MODE_HIDE))
1413 /* draw the new one */
1414 if (win.state & WIN_FOCUSED) {
1415 switch (win.cursor) {
1416 case 7: /* st extension: snowman */
1417 utf8decode("☃", &g.u, UTF_SIZ);
1418 case 0: /* Blinking Block */
1419 case 1: /* Blinking Block (Default) */
1420 case 2: /* Steady Block */
1421 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
1422 xdrawglyph(g, term.c.x, term.c.y);
1424 case 3: /* Blinking Underline */
1425 case 4: /* Steady Underline */
1426 XftDrawRect(xw.draw, &drawcol,
1427 borderpx + curx * win.cw,
1428 borderpx + (term.c.y + 1) * win.ch - \
1430 win.cw, cursorthickness);
1432 case 5: /* Blinking bar */
1433 case 6: /* Steady bar */
1434 XftDrawRect(xw.draw, &drawcol,
1435 borderpx + curx * win.cw,
1436 borderpx + term.c.y * win.ch,
1437 cursorthickness, win.ch);
1441 XftDrawRect(xw.draw, &drawcol,
1442 borderpx + curx * win.cw,
1443 borderpx + term.c.y * win.ch,
1445 XftDrawRect(xw.draw, &drawcol,
1446 borderpx + curx * win.cw,
1447 borderpx + term.c.y * win.ch,
1449 XftDrawRect(xw.draw, &drawcol,
1450 borderpx + (curx + 1) * win.cw - 1,
1451 borderpx + term.c.y * win.ch,
1453 XftDrawRect(xw.draw, &drawcol,
1454 borderpx + curx * win.cw,
1455 borderpx + (term.c.y + 1) * win.ch - 1,
1458 oldx = curx, oldy = term.c.y;
1464 char buf[sizeof(long) * 8 + 1];
1466 snprintf(buf, sizeof(buf), "%lu", xw.win);
1467 setenv("WINDOWID", buf, 1);
1475 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1477 XSetWMName(xw.dpy, xw.win, &prop);
1478 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1485 drawregion(0, 0, term.col, term.row);
1486 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1488 XSetForeground(xw.dpy, dc.gc,
1489 dc.col[IS_SET(MODE_REVERSE)?
1490 defaultfg : defaultbg].pixel);
1494 drawregion(int x1, int y1, int x2, int y2)
1496 int i, x, y, ox, numspecs;
1498 XftGlyphFontSpec *specs;
1499 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
1501 if (!(win.state & WIN_VISIBLE))
1504 for (y = y1; y < y2; y++) {
1511 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
1514 for (x = x1; x < x2 && i < numspecs; x++) {
1515 new = term.line[y][x];
1516 if (new.mode == ATTR_WDUMMY)
1518 if (ena_sel && selected(x, y))
1519 new.mode ^= ATTR_REVERSE;
1520 if (i > 0 && ATTRCMP(base, new)) {
1521 xdrawglyphfontspecs(specs, base, i, ox, y);
1533 xdrawglyphfontspecs(specs, base, i, ox, y);
1545 visibility(XEvent *ev)
1547 XVisibilityEvent *e = &ev->xvisibility;
1549 MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
1555 win.state &= ~WIN_VISIBLE;
1559 xsetpointermotion(int set)
1561 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1562 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1566 xseturgency(int add)
1568 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1570 MODBIT(h->flags, add, XUrgencyHint);
1571 XSetWMHints(xw.dpy, xw.win, h);
1578 if (!(win.state & WIN_FOCUSED))
1581 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1587 XFocusChangeEvent *e = &ev->xfocus;
1589 if (e->mode == NotifyGrab)
1592 if (ev->type == FocusIn) {
1593 XSetICFocus(xw.xic);
1594 win.state |= WIN_FOCUSED;
1596 if (IS_SET(MODE_FOCUS))
1597 ttywrite("\033[I", 3);
1599 XUnsetICFocus(xw.xic);
1600 win.state &= ~WIN_FOCUSED;
1601 if (IS_SET(MODE_FOCUS))
1602 ttywrite("\033[O", 3);
1609 XKeyEvent *e = &ev->xkey;
1611 char buf[32], *customkey;
1617 if (IS_SET(MODE_KBDLOCK))
1620 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1622 for (bp = shortcuts; bp < shortcuts + shortcutslen; bp++) {
1623 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1624 bp->func(&(bp->arg));
1629 /* 2. custom keys from config.h */
1630 if ((customkey = kmap(ksym, e->state))) {
1631 ttysend(customkey, strlen(customkey));
1635 /* 3. composed string from input method */
1638 if (len == 1 && e->state & Mod1Mask) {
1639 if (IS_SET(MODE_8BIT)) {
1642 len = utf8encode(c, buf);
1659 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1661 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1662 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1663 win.state |= WIN_FOCUSED;
1665 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1666 win.state &= ~WIN_FOCUSED;
1668 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1669 /* Send SIGHUP to shell */
1678 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1681 cresize(e->xconfigure.width, e->xconfigure.height);
1682 ttyresize(win.tw, win.th);
1689 int w = win.w, h = win.h;
1691 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1692 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1695 /* Waiting for window mapping */
1697 XNextEvent(xw.dpy, &ev);
1699 * This XFilterEvent call is required because of XOpenIM. It
1700 * does filter out the key event and some client message for
1701 * the input method too.
1703 if (XFilterEvent(&ev, None))
1705 if (ev.type == ConfigureNotify) {
1706 w = ev.xconfigure.width;
1707 h = ev.xconfigure.height;
1709 } while (ev.type != MapNotify);
1713 ttyresize(win.tw, win.th);
1715 clock_gettime(CLOCK_MONOTONIC, &last);
1718 for (xev = actionfps;;) {
1720 FD_SET(cmdfd, &rfd);
1723 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1726 die("select failed: %s\n", strerror(errno));
1728 if (FD_ISSET(cmdfd, &rfd)) {
1731 blinkset = tattrset(ATTR_BLINK);
1733 MODBIT(term.mode, 0, MODE_BLINK);
1737 if (FD_ISSET(xfd, &rfd))
1740 clock_gettime(CLOCK_MONOTONIC, &now);
1741 drawtimeout.tv_sec = 0;
1742 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1746 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1747 tsetdirtattr(ATTR_BLINK);
1748 term.mode ^= MODE_BLINK;
1752 deltatime = TIMEDIFF(now, last);
1753 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1759 while (XPending(xw.dpy)) {
1760 XNextEvent(xw.dpy, &ev);
1761 if (XFilterEvent(&ev, None))
1763 if (handler[ev.type])
1764 (handler[ev.type])(&ev);
1770 if (xev && !FD_ISSET(xfd, &rfd))
1772 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1774 if (TIMEDIFF(now, lastblink) \
1776 drawtimeout.tv_nsec = 1000;
1778 drawtimeout.tv_nsec = (1E6 * \
1783 drawtimeout.tv_sec = \
1784 drawtimeout.tv_nsec / 1E9;
1785 drawtimeout.tv_nsec %= (long)1E9;
1797 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1798 " [-n name] [-o file]\n"
1799 " [-T title] [-t title] [-w windowid]"
1800 " [[-e] command [args ...]]\n"
1801 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1802 " [-n name] [-o file]\n"
1803 " [-T title] [-t title] [-w windowid] -l line"
1804 " [stty_args ...]\n", argv0, argv0);
1808 main(int argc, char *argv[])
1812 win.cursor = cursorshape;
1819 opt_class = EARGF(usage());
1826 opt_font = EARGF(usage());
1829 xw.gm = XParseGeometry(EARGF(usage()),
1830 &xw.l, &xw.t, &cols, &rows);
1836 opt_io = EARGF(usage());
1839 opt_line = EARGF(usage());
1842 opt_name = EARGF(usage());
1846 opt_title = EARGF(usage());
1849 opt_embed = EARGF(usage());
1852 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
1860 /* eat all remaining arguments */
1862 if (!opt_title && !opt_line)
1863 opt_title = basename(xstrdup(argv[0]));
1865 setlocale(LC_CTYPE, "");
1866 XSetLocaleModifiers("");
1867 tnew(MAX(cols, 1), MAX(rows, 1));