1 /* See LICENSE for license details. */
7 #include <sys/select.h>
11 #include <X11/Xatom.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
24 /* types used in config.h */
28 void (*func)(const Arg *);
35 void (*func)(const Arg *);
44 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
45 signed char appkey; /* application keypad */
46 signed char appcursor; /* application cursor */
50 #define XK_ANY_MOD UINT_MAX
52 #define XK_SWITCH_MOD (1<<13)
54 /* function definitions used in config.h */
55 static void clipcopy(const Arg *);
56 static void clippaste(const Arg *);
57 static void numlock(const Arg *);
58 static void selpaste(const Arg *);
59 static void zoom(const Arg *);
60 static void zoomabs(const Arg *);
61 static void zoomreset(const Arg *);
62 static void ttysend(const Arg *);
64 /* config.h for applying patches and the configuration. */
68 #define XEMBED_FOCUS_IN 4
69 #define XEMBED_FOCUS_OUT 5
72 #define IS_SET(flag) ((win.mode & (flag)) != 0)
73 #define TRUERED(x) (((x) & 0xff0000) >> 8)
74 #define TRUEGREEN(x) (((x) & 0xff00))
75 #define TRUEBLUE(x) (((x) & 0xff) << 8)
77 typedef XftDraw *Draw;
78 typedef XftColor Color;
79 typedef XftGlyphFontSpec GlyphFontSpec;
81 /* Purely graphic info */
83 int tw, th; /* tty width and height */
84 int w, h; /* window width and height */
85 int ch; /* char height */
86 int cw; /* char width */
87 int mode; /* window state/mode flags */
88 int cursor; /* cursor style */
96 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
97 Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
102 XVaNestedList spotlist;
106 XSetWindowAttributes attrs;
108 int isfixed; /* is fixed geometry? */
109 int l, t; /* left and top offset */
110 int gm; /* geometry mask */
115 char *primary, *clipboard;
116 struct timespec tclick1;
117 struct timespec tclick2;
136 /* Drawing Context */
140 Font font, bfont, ifont, ibfont;
144 static inline ushort sixd_to_16bit(int);
145 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
146 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
147 static void xdrawglyph(Glyph, int, int);
148 static void xclear(int, int, int, int);
149 static int xgeommasktogravity(int);
150 static int ximopen(Display *);
151 static void ximinstantiate(Display *, XPointer, XPointer);
152 static void ximdestroy(XIM, XPointer, XPointer);
153 static int xicdestroy(XIC, XPointer, XPointer);
154 static void xinit(int, int);
155 static void cresize(int, int);
156 static void xresize(int, int);
157 static void xhints(void);
158 static int xloadcolor(int, const char *, Color *);
159 static int xloadfont(Font *, FcPattern *);
160 static void xloadfonts(const char *, double);
161 static void xunloadfont(Font *);
162 static void xunloadfonts(void);
163 static void xsetenv(void);
164 static void xseturgency(int);
165 static int evcol(XEvent *);
166 static int evrow(XEvent *);
168 static void expose(XEvent *);
169 static void visibility(XEvent *);
170 static void unmap(XEvent *);
171 static void kpress(XEvent *);
172 static void cmessage(XEvent *);
173 static void resize(XEvent *);
174 static void focus(XEvent *);
175 static uint buttonmask(uint);
176 static int mouseaction(XEvent *, uint);
177 static void brelease(XEvent *);
178 static void bpress(XEvent *);
179 static void bmotion(XEvent *);
180 static void propnotify(XEvent *);
181 static void selnotify(XEvent *);
182 static void selclear_(XEvent *);
183 static void selrequest(XEvent *);
184 static void setsel(char *, Time);
185 static void mousesel(XEvent *, int);
186 static void mousereport(XEvent *);
187 static char *kmap(KeySym, uint);
188 static int match(uint, uint);
190 static void run(void);
191 static void usage(void);
193 static void (*handler[LASTEvent])(XEvent *) = {
195 [ClientMessage] = cmessage,
196 [ConfigureNotify] = resize,
197 [VisibilityNotify] = visibility,
198 [UnmapNotify] = unmap,
202 [MotionNotify] = bmotion,
203 [ButtonPress] = bpress,
204 [ButtonRelease] = brelease,
206 * Uncomment if you want the selection to disappear when you select something
207 * different in another window.
209 /* [SelectionClear] = selclear_, */
210 [SelectionNotify] = selnotify,
212 * PropertyNotify is only turned on when there is some INCR transfer happening
213 * for the selection retrieval.
215 [PropertyNotify] = propnotify,
216 [SelectionRequest] = selrequest,
222 static XSelection xsel;
223 static TermWindow win;
225 /* Font Ring Cache */
239 /* Fontcache is an array now. A new font will be appended to the array. */
240 static Fontcache *frc = NULL;
241 static int frclen = 0;
242 static int frccap = 0;
243 static char *usedfont = NULL;
244 static double usedfontsize = 0;
245 static double defaultfontsize = 0;
247 static char *opt_class = NULL;
248 static char **opt_cmd = NULL;
249 static char *opt_embed = NULL;
250 static char *opt_font = NULL;
251 static char *opt_io = NULL;
252 static char *opt_line = NULL;
253 static char *opt_name = NULL;
254 static char *opt_title = NULL;
256 static int oldbutton = 3; /* button event on startup: 3 = release */
259 clipcopy(const Arg *dummy)
263 free(xsel.clipboard);
264 xsel.clipboard = NULL;
266 if (xsel.primary != NULL) {
267 xsel.clipboard = xstrdup(xsel.primary);
268 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
269 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
274 clippaste(const Arg *dummy)
278 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
279 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
280 xw.win, CurrentTime);
284 selpaste(const Arg *dummy)
286 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
287 xw.win, CurrentTime);
291 numlock(const Arg *dummy)
293 win.mode ^= MODE_NUMLOCK;
301 larg.f = usedfontsize + arg->f;
306 zoomabs(const Arg *arg)
309 xloadfonts(usedfont, arg->f);
316 zoomreset(const Arg *arg)
320 if (defaultfontsize > 0) {
321 larg.f = defaultfontsize;
327 ttysend(const Arg *arg)
329 ttywrite(arg->s, strlen(arg->s), 1);
335 int x = e->xbutton.x - borderpx;
336 LIMIT(x, 0, win.tw - 1);
343 int y = e->xbutton.y - borderpx;
344 LIMIT(y, 0, win.th - 1);
349 mousesel(XEvent *e, int done)
351 int type, seltype = SEL_REGULAR;
352 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
354 for (type = 1; type < LEN(selmasks); ++type) {
355 if (match(selmasks[type], state)) {
360 selextend(evcol(e), evrow(e), seltype, done);
362 setsel(getsel(), e->xbutton.time);
366 mousereport(XEvent *e)
368 int len, x = evcol(e), y = evrow(e),
369 button = e->xbutton.button, state = e->xbutton.state;
374 if (e->xbutton.type == MotionNotify) {
375 if (x == ox && y == oy)
377 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
379 /* MOUSE_MOTION: no reporting if no button is pressed */
380 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
383 button = oldbutton + 32;
387 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
393 else if (button >= 3)
396 if (e->xbutton.type == ButtonPress) {
400 } else if (e->xbutton.type == ButtonRelease) {
402 /* MODE_MOUSEX10: no button release reporting */
403 if (IS_SET(MODE_MOUSEX10))
405 if (button == 64 || button == 65)
410 if (!IS_SET(MODE_MOUSEX10)) {
411 button += ((state & ShiftMask ) ? 4 : 0)
412 + ((state & Mod4Mask ) ? 8 : 0)
413 + ((state & ControlMask) ? 16 : 0);
416 if (IS_SET(MODE_MOUSESGR)) {
417 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
419 e->xbutton.type == ButtonRelease ? 'm' : 'M');
420 } else if (x < 223 && y < 223) {
421 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
422 32+button, 32+x+1, 32+y+1);
427 ttywrite(buf, len, 0);
431 buttonmask(uint button)
433 return button == Button1 ? Button1Mask
434 : button == Button2 ? Button2Mask
435 : button == Button3 ? Button3Mask
436 : button == Button4 ? Button4Mask
437 : button == Button5 ? Button5Mask
442 mouseaction(XEvent *e, uint release)
446 /* ignore Button<N>mask for Button<N> - it's set on release */
447 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
449 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
450 if (ms->release == release &&
451 ms->button == e->xbutton.button &&
452 (match(ms->mod, state) || /* exact or forced */
453 match(ms->mod, state & ~forcemousemod))) {
454 ms->func(&(ms->arg));
468 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
473 if (mouseaction(e, 0))
476 if (e->xbutton.button == Button1) {
478 * If the user clicks below predefined timeouts specific
479 * snapping behaviour is exposed.
481 clock_gettime(CLOCK_MONOTONIC, &now);
482 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
484 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
489 xsel.tclick2 = xsel.tclick1;
492 selstart(evcol(e), evrow(e), snap);
497 propnotify(XEvent *e)
499 XPropertyEvent *xpev;
500 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
502 xpev = &e->xproperty;
503 if (xpev->state == PropertyNewValue &&
504 (xpev->atom == XA_PRIMARY ||
505 xpev->atom == clipboard)) {
513 ulong nitems, ofs, rem;
515 uchar *data, *last, *repl;
516 Atom type, incratom, property = None;
518 incratom = XInternAtom(xw.dpy, "INCR", 0);
521 if (e->type == SelectionNotify)
522 property = e->xselection.property;
523 else if (e->type == PropertyNotify)
524 property = e->xproperty.atom;
526 if (property == None)
530 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
531 BUFSIZ/4, False, AnyPropertyType,
532 &type, &format, &nitems, &rem,
534 fprintf(stderr, "Clipboard allocation failed\n");
538 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
540 * If there is some PropertyNotify with no data, then
541 * this is the signal of the selection owner that all
542 * data has been transferred. We won't need to receive
543 * PropertyNotify events anymore.
545 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
546 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
550 if (type == incratom) {
552 * Activate the PropertyNotify events so we receive
553 * when the selection owner does send us the next
556 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
557 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
561 * Deleting the property is the transfer start signal.
563 XDeleteProperty(xw.dpy, xw.win, (int)property);
569 * Line endings are inconsistent in the terminal and GUI world
570 * copy and pasting. When receiving some selection data,
571 * replace all '\n' with '\r'.
572 * FIXME: Fix the computer world.
575 last = data + nitems * format / 8;
576 while ((repl = memchr(repl, '\n', last - repl))) {
580 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
581 ttywrite("\033[200~", 6, 0);
582 ttywrite((char *)data, nitems * format / 8, 1);
583 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
584 ttywrite("\033[201~", 6, 0);
586 /* number of 32-bit chunks returned */
587 ofs += nitems * format / 32;
591 * Deleting the property again tells the selection owner to send the
592 * next data chunk in the property.
594 XDeleteProperty(xw.dpy, xw.win, (int)property);
610 selrequest(XEvent *e)
612 XSelectionRequestEvent *xsre;
614 Atom xa_targets, string, clipboard;
617 xsre = (XSelectionRequestEvent *) e;
618 xev.type = SelectionNotify;
619 xev.requestor = xsre->requestor;
620 xev.selection = xsre->selection;
621 xev.target = xsre->target;
622 xev.time = xsre->time;
623 if (xsre->property == None)
624 xsre->property = xsre->target;
629 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
630 if (xsre->target == xa_targets) {
631 /* respond with the supported type */
632 string = xsel.xtarget;
633 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
634 XA_ATOM, 32, PropModeReplace,
635 (uchar *) &string, 1);
636 xev.property = xsre->property;
637 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
639 * xith XA_STRING non ascii characters may be incorrect in the
640 * requestor. It is not our problem, use utf8.
642 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
643 if (xsre->selection == XA_PRIMARY) {
644 seltext = xsel.primary;
645 } else if (xsre->selection == clipboard) {
646 seltext = xsel.clipboard;
649 "Unhandled clipboard selection 0x%lx\n",
653 if (seltext != NULL) {
654 XChangeProperty(xsre->display, xsre->requestor,
655 xsre->property, xsre->target,
657 (uchar *)seltext, strlen(seltext));
658 xev.property = xsre->property;
662 /* all done, send a notification to the listener */
663 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
664 fprintf(stderr, "Error sending SelectionNotify event\n");
668 setsel(char *str, Time t)
676 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
677 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
684 setsel(str, CurrentTime);
690 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
695 if (mouseaction(e, 1))
697 if (e->xbutton.button == Button1)
704 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
713 cresize(int width, int height)
722 col = (win.w - 2 * borderpx) / win.cw;
723 row = (win.h - 2 * borderpx) / win.ch;
729 ttyresize(win.tw, win.th);
733 xresize(int col, int row)
735 win.tw = col * win.cw;
736 win.th = row * win.ch;
738 XFreePixmap(xw.dpy, xw.buf);
739 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
740 DefaultDepth(xw.dpy, xw.scr));
741 XftDrawChange(xw.draw, xw.buf);
742 xclear(0, 0, win.w, win.h);
744 /* resize to new width */
745 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
751 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
755 xloadcolor(int i, const char *name, Color *ncolor)
757 XRenderColor color = { .alpha = 0xffff };
760 if (BETWEEN(i, 16, 255)) { /* 256 color */
761 if (i < 6*6*6+16) { /* same colors as xterm */
762 color.red = sixd_to_16bit( ((i-16)/36)%6 );
763 color.green = sixd_to_16bit( ((i-16)/6) %6 );
764 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
765 } else { /* greyscale */
766 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
767 color.green = color.blue = color.red;
769 return XftColorAllocValue(xw.dpy, xw.vis,
770 xw.cmap, &color, ncolor);
775 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
786 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
787 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
789 dc.collen = MAX(LEN(colorname), 256);
790 dc.col = xmalloc(dc.collen * sizeof(Color));
793 for (i = 0; i < dc.collen; i++)
794 if (!xloadcolor(i, NULL, &dc.col[i])) {
796 die("could not allocate color '%s'\n", colorname[i]);
798 die("could not allocate color %d\n", i);
804 xsetcolorname(int x, const char *name)
808 if (!BETWEEN(x, 0, dc.collen))
811 if (!xloadcolor(x, name, &ncolor))
814 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
821 * Absolute coordinates.
824 xclear(int x1, int y1, int x2, int y2)
827 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
828 x1, y1, x2-x1, y2-y1);
834 XClassHint class = {opt_name ? opt_name : termname,
835 opt_class ? opt_class : termname};
836 XWMHints wm = {.flags = InputHint, .input = 1};
839 sizeh = XAllocSizeHints();
841 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
842 sizeh->height = win.h;
843 sizeh->width = win.w;
844 sizeh->height_inc = win.ch;
845 sizeh->width_inc = win.cw;
846 sizeh->base_height = 2 * borderpx;
847 sizeh->base_width = 2 * borderpx;
848 sizeh->min_height = win.ch + 2 * borderpx;
849 sizeh->min_width = win.cw + 2 * borderpx;
851 sizeh->flags |= PMaxSize;
852 sizeh->min_width = sizeh->max_width = win.w;
853 sizeh->min_height = sizeh->max_height = win.h;
855 if (xw.gm & (XValue|YValue)) {
856 sizeh->flags |= USPosition | PWinGravity;
859 sizeh->win_gravity = xgeommasktogravity(xw.gm);
862 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
868 xgeommasktogravity(int mask)
870 switch (mask & (XNegative|YNegative)) {
872 return NorthWestGravity;
874 return NorthEastGravity;
876 return SouthWestGravity;
879 return SouthEastGravity;
883 xloadfont(Font *f, FcPattern *pattern)
885 FcPattern *configured;
889 int wantattr, haveattr;
892 * Manually configure instead of calling XftMatchFont
893 * so that we can use the configured pattern for
894 * "missing glyph" lookups.
896 configured = FcPatternDuplicate(pattern);
900 FcConfigSubstitute(NULL, configured, FcMatchPattern);
901 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
903 match = FcFontMatch(NULL, configured, &result);
905 FcPatternDestroy(configured);
909 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
910 FcPatternDestroy(configured);
911 FcPatternDestroy(match);
915 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
918 * Check if xft was unable to find a font with the appropriate
919 * slant but gave us one anyway. Try to mitigate.
921 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
922 &haveattr) != XftResultMatch) || haveattr < wantattr) {
924 fputs("font slant does not match\n", stderr);
928 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
930 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
931 &haveattr) != XftResultMatch) || haveattr != wantattr) {
933 fputs("font weight does not match\n", stderr);
937 XftTextExtentsUtf8(xw.dpy, f->match,
938 (const FcChar8 *) ascii_printable,
939 strlen(ascii_printable), &extents);
942 f->pattern = configured;
944 f->ascent = f->match->ascent;
945 f->descent = f->match->descent;
947 f->rbearing = f->match->max_advance_width;
949 f->height = f->ascent + f->descent;
950 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
956 xloadfonts(const char *fontstr, double fontsize)
961 if (fontstr[0] == '-')
962 pattern = XftXlfdParse(fontstr, False, False);
964 pattern = FcNameParse((const FcChar8 *)fontstr);
967 die("can't open font %s\n", fontstr);
970 FcPatternDel(pattern, FC_PIXEL_SIZE);
971 FcPatternDel(pattern, FC_SIZE);
972 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
973 usedfontsize = fontsize;
975 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
977 usedfontsize = fontval;
978 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
983 * Default font size is 12, if none given. This is to
984 * have a known usedfontsize value.
986 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
989 defaultfontsize = usedfontsize;
992 if (xloadfont(&dc.font, pattern))
993 die("can't open font %s\n", fontstr);
995 if (usedfontsize < 0) {
996 FcPatternGetDouble(dc.font.match->pattern,
997 FC_PIXEL_SIZE, 0, &fontval);
998 usedfontsize = fontval;
1000 defaultfontsize = fontval;
1003 /* Setting character width and height. */
1004 win.cw = ceilf(dc.font.width * cwscale);
1005 win.ch = ceilf(dc.font.height * chscale);
1007 FcPatternDel(pattern, FC_SLANT);
1008 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1009 if (xloadfont(&dc.ifont, pattern))
1010 die("can't open font %s\n", fontstr);
1012 FcPatternDel(pattern, FC_WEIGHT);
1013 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1014 if (xloadfont(&dc.ibfont, pattern))
1015 die("can't open font %s\n", fontstr);
1017 FcPatternDel(pattern, FC_SLANT);
1018 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1019 if (xloadfont(&dc.bfont, pattern))
1020 die("can't open font %s\n", fontstr);
1022 FcPatternDestroy(pattern);
1026 xunloadfont(Font *f)
1028 XftFontClose(xw.dpy, f->match);
1029 FcPatternDestroy(f->pattern);
1031 FcFontSetDestroy(f->set);
1037 /* Clear Harfbuzz font cache. */
1040 /* Free the loaded fonts in the font cache. */
1042 XftFontClose(xw.dpy, frc[--frclen].font);
1044 xunloadfont(&dc.font);
1045 xunloadfont(&dc.bfont);
1046 xunloadfont(&dc.ifont);
1047 xunloadfont(&dc.ibfont);
1051 ximopen(Display *dpy)
1053 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1054 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1056 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1057 if (xw.ime.xim == NULL)
1060 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1061 fprintf(stderr, "XSetIMValues: "
1062 "Could not set XNDestroyCallback.\n");
1064 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1067 if (xw.ime.xic == NULL) {
1068 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1069 XIMPreeditNothing | XIMStatusNothing,
1070 XNClientWindow, xw.win,
1071 XNDestroyCallback, &icdestroy,
1074 if (xw.ime.xic == NULL)
1075 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1081 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1084 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1085 ximinstantiate, NULL);
1089 ximdestroy(XIM xim, XPointer client, XPointer call)
1092 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1093 ximinstantiate, NULL);
1094 XFree(xw.ime.spotlist);
1098 xicdestroy(XIC xim, XPointer client, XPointer call)
1105 xinit(int cols, int rows)
1110 pid_t thispid = getpid();
1111 XColor xmousefg, xmousebg;
1113 if (!(xw.dpy = XOpenDisplay(NULL)))
1114 die("can't open display\n");
1115 xw.scr = XDefaultScreen(xw.dpy);
1116 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1120 die("could not init fontconfig.\n");
1122 usedfont = (opt_font == NULL)? font : opt_font;
1123 xloadfonts(usedfont, 0);
1126 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1129 /* adjust fixed window geometry */
1130 win.w = 2 * borderpx + cols * win.cw;
1131 win.h = 2 * borderpx + rows * win.ch;
1132 if (xw.gm & XNegative)
1133 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1134 if (xw.gm & YNegative)
1135 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1138 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1139 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1140 xw.attrs.bit_gravity = NorthWestGravity;
1141 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1142 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1143 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1144 xw.attrs.colormap = xw.cmap;
1146 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1147 parent = XRootWindow(xw.dpy, xw.scr);
1148 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1149 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1150 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1151 | CWEventMask | CWColormap, &xw.attrs);
1153 memset(&gcvalues, 0, sizeof(gcvalues));
1154 gcvalues.graphics_exposures = False;
1155 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1157 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1158 DefaultDepth(xw.dpy, xw.scr));
1159 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1160 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1162 /* font spec buffer */
1163 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1165 /* Xft rendering context */
1166 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1169 if (!ximopen(xw.dpy)) {
1170 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1171 ximinstantiate, NULL);
1174 /* white cursor, black outline */
1175 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1176 XDefineCursor(xw.dpy, xw.win, cursor);
1178 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1179 xmousefg.red = 0xffff;
1180 xmousefg.green = 0xffff;
1181 xmousefg.blue = 0xffff;
1184 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1185 xmousebg.red = 0x0000;
1186 xmousebg.green = 0x0000;
1187 xmousebg.blue = 0x0000;
1190 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1192 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1193 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1194 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1195 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1196 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1198 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1199 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1200 PropModeReplace, (uchar *)&thispid, 1);
1202 win.mode = MODE_NUMLOCK;
1205 XMapWindow(xw.dpy, xw.win);
1206 XSync(xw.dpy, False);
1208 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1209 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1210 xsel.primary = NULL;
1211 xsel.clipboard = NULL;
1212 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1213 if (xsel.xtarget == None)
1214 xsel.xtarget = XA_STRING;
1218 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1220 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1221 ushort mode, prevmode = USHRT_MAX;
1222 Font *font = &dc.font;
1223 int frcflags = FRC_NORMAL;
1224 float runewidth = win.cw;
1228 FcPattern *fcpattern, *fontpattern;
1229 FcFontSet *fcsets[] = { NULL };
1230 FcCharSet *fccharset;
1231 int i, f, numspecs = 0;
1233 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1234 /* Fetch rune and mode for current glyph. */
1236 mode = glyphs[i].mode;
1238 /* Skip dummy wide-character spacing. */
1239 if (mode & ATTR_WDUMMY)
1242 /* Determine font for glyph if different from previous glyph. */
1243 if (prevmode != mode) {
1246 frcflags = FRC_NORMAL;
1247 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1248 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1250 frcflags = FRC_ITALICBOLD;
1251 } else if (mode & ATTR_ITALIC) {
1253 frcflags = FRC_ITALIC;
1254 } else if (mode & ATTR_BOLD) {
1256 frcflags = FRC_BOLD;
1258 yp = winy + font->ascent;
1261 /* Lookup character index with default font. */
1262 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1264 specs[numspecs].font = font->match;
1265 specs[numspecs].glyph = glyphidx;
1266 specs[numspecs].x = (short)xp;
1267 specs[numspecs].y = (short)yp;
1273 /* Fallback on font cache, search the font cache for match. */
1274 for (f = 0; f < frclen; f++) {
1275 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1276 /* Everything correct. */
1277 if (glyphidx && frc[f].flags == frcflags)
1279 /* We got a default font for a not found glyph. */
1280 if (!glyphidx && frc[f].flags == frcflags
1281 && frc[f].unicodep == rune) {
1286 /* Nothing was found. Use fontconfig to find matching font. */
1289 font->set = FcFontSort(0, font->pattern,
1291 fcsets[0] = font->set;
1294 * Nothing was found in the cache. Now use
1295 * some dozen of Fontconfig calls to get the
1296 * font for one single character.
1298 * Xft and fontconfig are design failures.
1300 fcpattern = FcPatternDuplicate(font->pattern);
1301 fccharset = FcCharSetCreate();
1303 FcCharSetAddChar(fccharset, rune);
1304 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1306 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1308 FcConfigSubstitute(0, fcpattern,
1310 FcDefaultSubstitute(fcpattern);
1312 fontpattern = FcFontSetMatch(0, fcsets, 1,
1315 /* Allocate memory for the new cache entry. */
1316 if (frclen >= frccap) {
1318 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1321 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1323 if (!frc[frclen].font)
1324 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1326 frc[frclen].flags = frcflags;
1327 frc[frclen].unicodep = rune;
1329 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1334 FcPatternDestroy(fcpattern);
1335 FcCharSetDestroy(fccharset);
1338 specs[numspecs].font = frc[f].font;
1339 specs[numspecs].glyph = glyphidx;
1340 specs[numspecs].x = (short)xp;
1341 specs[numspecs].y = (short)yp;
1346 /* Harfbuzz transformation for ligatures. */
1347 hbtransform(specs, glyphs, len, x, y);
1353 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1355 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1356 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1357 width = charlen * win.cw;
1358 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1359 XRenderColor colfg, colbg;
1362 /* Fallback on color display for attributes not supported by the font */
1363 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1364 if (dc.ibfont.badslant || dc.ibfont.badweight)
1365 base.fg = defaultattr;
1366 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1367 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1368 base.fg = defaultattr;
1371 if (IS_TRUECOL(base.fg)) {
1372 colfg.alpha = 0xffff;
1373 colfg.red = TRUERED(base.fg);
1374 colfg.green = TRUEGREEN(base.fg);
1375 colfg.blue = TRUEBLUE(base.fg);
1376 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1379 fg = &dc.col[base.fg];
1382 if (IS_TRUECOL(base.bg)) {
1383 colbg.alpha = 0xffff;
1384 colbg.green = TRUEGREEN(base.bg);
1385 colbg.red = TRUERED(base.bg);
1386 colbg.blue = TRUEBLUE(base.bg);
1387 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1390 bg = &dc.col[base.bg];
1393 /* Change basic system colors [0-7] to bright system colors [8-15] */
1394 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1395 fg = &dc.col[base.fg + 8];
1397 if (IS_SET(MODE_REVERSE)) {
1398 if (fg == &dc.col[defaultfg]) {
1399 fg = &dc.col[defaultbg];
1401 colfg.red = ~fg->color.red;
1402 colfg.green = ~fg->color.green;
1403 colfg.blue = ~fg->color.blue;
1404 colfg.alpha = fg->color.alpha;
1405 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1410 if (bg == &dc.col[defaultbg]) {
1411 bg = &dc.col[defaultfg];
1413 colbg.red = ~bg->color.red;
1414 colbg.green = ~bg->color.green;
1415 colbg.blue = ~bg->color.blue;
1416 colbg.alpha = bg->color.alpha;
1417 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1423 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1424 colfg.red = fg->color.red / 2;
1425 colfg.green = fg->color.green / 2;
1426 colfg.blue = fg->color.blue / 2;
1427 colfg.alpha = fg->color.alpha;
1428 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1432 if (base.mode & ATTR_REVERSE) {
1438 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1441 if (base.mode & ATTR_INVISIBLE)
1444 /* Intelligent cleaning up of the borders. */
1446 xclear(0, (y == 0)? 0 : winy, borderpx,
1448 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1450 if (winx + width >= borderpx + win.tw) {
1451 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1452 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1455 xclear(winx, 0, winx + width, borderpx);
1456 if (winy + win.ch >= borderpx + win.th)
1457 xclear(winx, winy + win.ch, winx + width, win.h);
1459 /* Clean up the region we want to draw to. */
1460 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1462 /* Set the clip region because Xft is sometimes dirty. */
1467 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1469 /* Render the glyphs. */
1470 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1472 /* Render underline and strikethrough. */
1473 if (base.mode & ATTR_UNDERLINE) {
1474 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1478 if (base.mode & ATTR_STRUCK) {
1479 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1483 /* Reset clip to none. */
1484 XftDrawSetClip(xw.draw, 0);
1488 xdrawglyph(Glyph g, int x, int y)
1491 XftGlyphFontSpec spec;
1493 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1494 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1498 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og, Line line, int len)
1502 /* remove the old cursor */
1503 if (selected(ox, oy))
1504 og.mode ^= ATTR_REVERSE;
1506 /* Redraw the line where cursor was previously.
1507 * It will restore the ligatures broken by the cursor. */
1508 xdrawline(line, 0, oy, len);
1510 if (IS_SET(MODE_HIDE))
1514 * Select the right color for the right mode.
1516 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1518 if (IS_SET(MODE_REVERSE)) {
1519 g.mode |= ATTR_REVERSE;
1521 if (selected(cx, cy)) {
1522 drawcol = dc.col[defaultcs];
1525 drawcol = dc.col[defaultrcs];
1529 if (selected(cx, cy)) {
1536 drawcol = dc.col[g.bg];
1539 /* draw the new one */
1540 if (IS_SET(MODE_FOCUSED)) {
1541 switch (win.cursor) {
1542 case 7: /* st extension */
1543 g.u = 0x2603; /* snowman (U+2603) */
1545 case 0: /* Blinking Block */
1546 case 1: /* Blinking Block (Default) */
1547 case 2: /* Steady Block */
1548 xdrawglyph(g, cx, cy);
1550 case 3: /* Blinking Underline */
1551 case 4: /* Steady Underline */
1552 XftDrawRect(xw.draw, &drawcol,
1553 borderpx + cx * win.cw,
1554 borderpx + (cy + 1) * win.ch - \
1556 win.cw, cursorthickness);
1558 case 5: /* Blinking bar */
1559 case 6: /* Steady bar */
1560 XftDrawRect(xw.draw, &drawcol,
1561 borderpx + cx * win.cw,
1562 borderpx + cy * win.ch,
1563 cursorthickness, win.ch);
1567 XftDrawRect(xw.draw, &drawcol,
1568 borderpx + cx * win.cw,
1569 borderpx + cy * win.ch,
1571 XftDrawRect(xw.draw, &drawcol,
1572 borderpx + cx * win.cw,
1573 borderpx + cy * win.ch,
1575 XftDrawRect(xw.draw, &drawcol,
1576 borderpx + (cx + 1) * win.cw - 1,
1577 borderpx + cy * win.ch,
1579 XftDrawRect(xw.draw, &drawcol,
1580 borderpx + cx * win.cw,
1581 borderpx + (cy + 1) * win.ch - 1,
1589 char buf[sizeof(long) * 8 + 1];
1591 snprintf(buf, sizeof(buf), "%lu", xw.win);
1592 setenv("WINDOWID", buf, 1);
1596 xseticontitle(char *p)
1599 DEFAULT(p, opt_title);
1601 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1603 XSetWMIconName(xw.dpy, xw.win, &prop);
1604 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1612 DEFAULT(p, opt_title);
1614 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1616 XSetWMName(xw.dpy, xw.win, &prop);
1617 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1624 return IS_SET(MODE_VISIBLE);
1628 xdrawline(Line line, int x1, int y1, int x2)
1630 int i, x, ox, numspecs;
1632 XftGlyphFontSpec *specs = xw.specbuf;
1634 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1636 for (x = x1; x < x2 && i < numspecs; x++) {
1638 if (new.mode == ATTR_WDUMMY)
1640 if (selected(x, y1))
1641 new.mode ^= ATTR_REVERSE;
1642 if (i > 0 && ATTRCMP(base, new)) {
1643 xdrawglyphfontspecs(specs, base, i, ox, y1);
1655 xdrawglyphfontspecs(specs, base, i, ox, y1);
1661 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1663 XSetForeground(xw.dpy, dc.gc,
1664 dc.col[IS_SET(MODE_REVERSE)?
1665 defaultfg : defaultbg].pixel);
1669 xximspot(int x, int y)
1671 if (xw.ime.xic == NULL)
1674 xw.ime.spot.x = borderpx + x * win.cw;
1675 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1677 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1687 visibility(XEvent *ev)
1689 XVisibilityEvent *e = &ev->xvisibility;
1691 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1697 win.mode &= ~MODE_VISIBLE;
1701 xsetpointermotion(int set)
1703 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1704 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1708 xsetmode(int set, unsigned int flags)
1710 int mode = win.mode;
1711 MODBIT(win.mode, set, flags);
1712 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1717 xsetcursor(int cursor)
1719 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
1721 win.cursor = cursor;
1726 xseturgency(int add)
1728 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1730 MODBIT(h->flags, add, XUrgencyHint);
1731 XSetWMHints(xw.dpy, xw.win, h);
1738 if (!(IS_SET(MODE_FOCUSED)))
1741 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1747 XFocusChangeEvent *e = &ev->xfocus;
1749 if (e->mode == NotifyGrab)
1752 if (ev->type == FocusIn) {
1754 XSetICFocus(xw.ime.xic);
1755 win.mode |= MODE_FOCUSED;
1757 if (IS_SET(MODE_FOCUS))
1758 ttywrite("\033[I", 3, 0);
1761 XUnsetICFocus(xw.ime.xic);
1762 win.mode &= ~MODE_FOCUSED;
1763 if (IS_SET(MODE_FOCUS))
1764 ttywrite("\033[O", 3, 0);
1769 match(uint mask, uint state)
1771 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1775 kmap(KeySym k, uint state)
1780 /* Check for mapped keys out of X11 function keys. */
1781 for (i = 0; i < LEN(mappedkeys); i++) {
1782 if (mappedkeys[i] == k)
1785 if (i == LEN(mappedkeys)) {
1786 if ((k & 0xFFFF) < 0xFD00)
1790 for (kp = key; kp < key + LEN(key); kp++) {
1794 if (!match(kp->mask, state))
1797 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1799 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1802 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1814 XKeyEvent *e = &ev->xkey;
1816 char buf[64], *customkey;
1822 if (IS_SET(MODE_KBDLOCK))
1826 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1828 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1830 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1831 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1832 bp->func(&(bp->arg));
1837 /* 2. custom keys from config.h */
1838 if ((customkey = kmap(ksym, e->state))) {
1839 ttywrite(customkey, strlen(customkey), 1);
1843 /* 3. composed string from input method */
1846 if (len == 1 && e->state & Mod1Mask) {
1847 if (IS_SET(MODE_8BIT)) {
1850 len = utf8encode(c, buf);
1858 ttywrite(buf, len, 1);
1866 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1868 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1869 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1870 win.mode |= MODE_FOCUSED;
1872 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1873 win.mode &= ~MODE_FOCUSED;
1875 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1884 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1887 cresize(e->xconfigure.width, e->xconfigure.height);
1894 int w = win.w, h = win.h;
1896 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1897 struct timespec seltv, *tv, now, lastblink, trigger;
1900 /* Waiting for window mapping */
1902 XNextEvent(xw.dpy, &ev);
1904 * This XFilterEvent call is required because of XOpenIM. It
1905 * does filter out the key event and some client message for
1906 * the input method too.
1908 if (XFilterEvent(&ev, None))
1910 if (ev.type == ConfigureNotify) {
1911 w = ev.xconfigure.width;
1912 h = ev.xconfigure.height;
1914 } while (ev.type != MapNotify);
1916 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1919 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1921 FD_SET(ttyfd, &rfd);
1924 if (XPending(xw.dpy))
1925 timeout = 0; /* existing events might not set xfd */
1927 seltv.tv_sec = timeout / 1E3;
1928 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1929 tv = timeout >= 0 ? &seltv : NULL;
1931 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1934 die("select failed: %s\n", strerror(errno));
1936 clock_gettime(CLOCK_MONOTONIC, &now);
1938 if (FD_ISSET(ttyfd, &rfd))
1942 while (XPending(xw.dpy)) {
1944 XNextEvent(xw.dpy, &ev);
1945 if (XFilterEvent(&ev, None))
1947 if (handler[ev.type])
1948 (handler[ev.type])(&ev);
1952 * To reduce flicker and tearing, when new content or event
1953 * triggers drawing, we first wait a bit to ensure we got
1954 * everything, and if nothing new arrives - we draw.
1955 * We start with trying to wait minlatency ms. If more content
1956 * arrives sooner, we retry with shorter and shorter periods,
1957 * and eventually draw even without idle after maxlatency ms.
1958 * Typically this results in low latency while interacting,
1959 * maximum latency intervals during `cat huge.txt`, and perfect
1960 * sync with periodic updates from animations/key-repeats/etc.
1962 if (FD_ISSET(ttyfd, &rfd) || xev) {
1967 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1968 / maxlatency * minlatency;
1970 continue; /* we have time, try to find idle */
1973 /* idle detected or maxlatency exhausted -> draw */
1975 if (blinktimeout && tattrset(ATTR_BLINK)) {
1976 timeout = blinktimeout - TIMEDIFF(now, lastblink);
1978 if (-timeout > blinktimeout) /* start visible */
1979 win.mode |= MODE_BLINK;
1980 win.mode ^= MODE_BLINK;
1981 tsetdirtattr(ATTR_BLINK);
1983 timeout = blinktimeout;
1996 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1997 " [-n name] [-o file]\n"
1998 " [-T title] [-t title] [-w windowid]"
1999 " [[-e] command [args ...]]\n"
2000 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2001 " [-n name] [-o file]\n"
2002 " [-T title] [-t title] [-w windowid] -l line"
2003 " [stty_args ...]\n", argv0, argv0);
2007 main(int argc, char *argv[])
2011 xsetcursor(cursorshape);
2018 opt_class = EARGF(usage());
2025 opt_font = EARGF(usage());
2028 xw.gm = XParseGeometry(EARGF(usage()),
2029 &xw.l, &xw.t, &cols, &rows);
2035 opt_io = EARGF(usage());
2038 opt_line = EARGF(usage());
2041 opt_name = EARGF(usage());
2045 opt_title = EARGF(usage());
2048 opt_embed = EARGF(usage());
2051 die("%s " VERSION "\n", argv0);
2058 if (argc > 0) /* eat all remaining arguments */
2062 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2064 setlocale(LC_CTYPE, "");
2065 XSetLocaleModifiers("");
2066 cols = MAX(cols, 1);
2067 rows = MAX(rows, 1);