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>
23 /* types used in config.h */
27 void (*func)(const Arg *);
34 void (*func)(const Arg *);
43 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
44 signed char appkey; /* application keypad */
45 signed char appcursor; /* application cursor */
49 #define XK_ANY_MOD UINT_MAX
51 #define XK_SWITCH_MOD (1<<13|1<<14)
53 /* function definitions used in config.h */
54 static void clipcopy(const Arg *);
55 static void clippaste(const Arg *);
56 static void numlock(const Arg *);
57 static void selpaste(const Arg *);
58 static void zoom(const Arg *);
59 static void zoomabs(const Arg *);
60 static void zoomreset(const Arg *);
61 static void ttysend(const Arg *);
63 /* config.h for applying patches and the configuration. */
67 #define XEMBED_FOCUS_IN 4
68 #define XEMBED_FOCUS_OUT 5
71 #define IS_SET(flag) ((win.mode & (flag)) != 0)
72 #define TRUERED(x) (((x) & 0xff0000) >> 8)
73 #define TRUEGREEN(x) (((x) & 0xff00))
74 #define TRUEBLUE(x) (((x) & 0xff) << 8)
76 typedef XftDraw *Draw;
77 typedef XftColor Color;
78 typedef XftGlyphFontSpec GlyphFontSpec;
80 /* Purely graphic info */
82 int tw, th; /* tty width and height */
83 int w, h; /* window width and height */
84 int ch; /* char height */
85 int cw; /* char width */
86 int mode; /* window state/mode flags */
87 int cursor; /* cursor style */
95 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
96 Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
101 XVaNestedList spotlist;
105 XSetWindowAttributes attrs;
107 int isfixed; /* is fixed geometry? */
108 int l, t; /* left and top offset */
109 int gm; /* geometry mask */
114 char *primary, *clipboard;
115 struct timespec tclick1;
116 struct timespec tclick2;
135 /* Drawing Context */
139 Font font, bfont, ifont, ibfont;
143 static inline ushort sixd_to_16bit(int);
144 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
145 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
146 static void xdrawglyph(Glyph, int, int);
147 static void xclear(int, int, int, int);
148 static int xgeommasktogravity(int);
149 static int ximopen(Display *);
150 static void ximinstantiate(Display *, XPointer, XPointer);
151 static void ximdestroy(XIM, XPointer, XPointer);
152 static int xicdestroy(XIC, XPointer, XPointer);
153 static void xinit(int, int);
154 static void cresize(int, int);
155 static void xresize(int, int);
156 static void xhints(void);
157 static int xloadcolor(int, const char *, Color *);
158 static int xloadfont(Font *, FcPattern *);
159 static void xloadfonts(const char *, double);
160 static void xunloadfont(Font *);
161 static void xunloadfonts(void);
162 static void xsetenv(void);
163 static void xseturgency(int);
164 static int evcol(XEvent *);
165 static int evrow(XEvent *);
167 static void expose(XEvent *);
168 static void visibility(XEvent *);
169 static void unmap(XEvent *);
170 static void kpress(XEvent *);
171 static void cmessage(XEvent *);
172 static void resize(XEvent *);
173 static void focus(XEvent *);
174 static uint buttonmask(uint);
175 static int mouseaction(XEvent *, uint);
176 static void brelease(XEvent *);
177 static void bpress(XEvent *);
178 static void bmotion(XEvent *);
179 static void propnotify(XEvent *);
180 static void selnotify(XEvent *);
181 static void selclear_(XEvent *);
182 static void selrequest(XEvent *);
183 static void setsel(char *, Time);
184 static void mousesel(XEvent *, int);
185 static void mousereport(XEvent *);
186 static char *kmap(KeySym, uint);
187 static int match(uint, uint);
189 static void run(void);
190 static void usage(void);
192 static void (*handler[LASTEvent])(XEvent *) = {
194 [ClientMessage] = cmessage,
195 [ConfigureNotify] = resize,
196 [VisibilityNotify] = visibility,
197 [UnmapNotify] = unmap,
201 [MotionNotify] = bmotion,
202 [ButtonPress] = bpress,
203 [ButtonRelease] = brelease,
205 * Uncomment if you want the selection to disappear when you select something
206 * different in another window.
208 /* [SelectionClear] = selclear_, */
209 [SelectionNotify] = selnotify,
211 * PropertyNotify is only turned on when there is some INCR transfer happening
212 * for the selection retrieval.
214 [PropertyNotify] = propnotify,
215 [SelectionRequest] = selrequest,
221 static XSelection xsel;
222 static TermWindow win;
224 /* Font Ring Cache */
238 /* Fontcache is an array now. A new font will be appended to the array. */
239 static Fontcache *frc = NULL;
240 static int frclen = 0;
241 static int frccap = 0;
242 static char *usedfont = NULL;
243 static double usedfontsize = 0;
244 static double defaultfontsize = 0;
246 static char *opt_class = NULL;
247 static char **opt_cmd = NULL;
248 static char *opt_embed = NULL;
249 static char *opt_font = NULL;
250 static char *opt_io = NULL;
251 static char *opt_line = NULL;
252 static char *opt_name = NULL;
253 static char *opt_title = NULL;
255 static uint buttons; /* bit field of pressed buttons */
256 static int cursorblinks = 0;
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)
369 int x = evcol(e), y = evrow(e);
370 int state = e->xbutton.state;
374 if (e->type == MotionNotify) {
375 if (x == ox && y == oy)
377 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
379 /* MODE_MOUSEMOTION: no reporting if no button is pressed */
380 if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
382 /* Set btn to lowest-numbered pressed button, or 12 if no
383 * buttons are pressed. */
384 for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++)
388 btn = e->xbutton.button;
389 /* Only buttons 1 through 11 can be encoded */
390 if (btn < 1 || btn > 11)
392 if (e->type == ButtonRelease) {
393 /* MODE_MOUSEX10: no button release reporting */
394 if (IS_SET(MODE_MOUSEX10))
396 /* Don't send release events for the scroll wheel */
397 if (btn == 4 || btn == 5)
406 /* Encode btn into code. If no button is pressed for a motion event in
407 * MODE_MOUSEMANY, then encode it as a release. */
408 if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12)
411 code += 128 + btn - 8;
413 code += 64 + btn - 4;
417 if (!IS_SET(MODE_MOUSEX10)) {
418 code += ((state & ShiftMask ) ? 4 : 0)
419 + ((state & Mod1Mask ) ? 8 : 0) /* meta key: alt */
420 + ((state & ControlMask) ? 16 : 0);
423 if (IS_SET(MODE_MOUSESGR)) {
424 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
426 e->type == ButtonRelease ? 'm' : 'M');
427 } else if (x < 223 && y < 223) {
428 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
429 32+code, 32+x+1, 32+y+1);
434 ttywrite(buf, len, 0);
438 buttonmask(uint button)
440 return button == Button1 ? Button1Mask
441 : button == Button2 ? Button2Mask
442 : button == Button3 ? Button3Mask
443 : button == Button4 ? Button4Mask
444 : button == Button5 ? Button5Mask
449 mouseaction(XEvent *e, uint release)
453 /* ignore Button<N>mask for Button<N> - it's set on release */
454 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
456 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
457 if (ms->release == release &&
458 ms->button == e->xbutton.button &&
459 (match(ms->mod, state) || /* exact or forced */
460 match(ms->mod, state & ~forcemousemod))) {
461 ms->func(&(ms->arg));
472 int btn = e->xbutton.button;
476 if (1 <= btn && btn <= 11)
477 buttons |= 1 << (btn-1);
479 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
484 if (mouseaction(e, 0))
487 if (btn == Button1) {
489 * If the user clicks below predefined timeouts specific
490 * snapping behaviour is exposed.
492 clock_gettime(CLOCK_MONOTONIC, &now);
493 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
495 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
500 xsel.tclick2 = xsel.tclick1;
503 selstart(evcol(e), evrow(e), snap);
508 propnotify(XEvent *e)
510 XPropertyEvent *xpev;
511 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
513 xpev = &e->xproperty;
514 if (xpev->state == PropertyNewValue &&
515 (xpev->atom == XA_PRIMARY ||
516 xpev->atom == clipboard)) {
524 ulong nitems, ofs, rem;
526 uchar *data, *last, *repl;
527 Atom type, incratom, property = None;
529 incratom = XInternAtom(xw.dpy, "INCR", 0);
532 if (e->type == SelectionNotify)
533 property = e->xselection.property;
534 else if (e->type == PropertyNotify)
535 property = e->xproperty.atom;
537 if (property == None)
541 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
542 BUFSIZ/4, False, AnyPropertyType,
543 &type, &format, &nitems, &rem,
545 fprintf(stderr, "Clipboard allocation failed\n");
549 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
551 * If there is some PropertyNotify with no data, then
552 * this is the signal of the selection owner that all
553 * data has been transferred. We won't need to receive
554 * PropertyNotify events anymore.
556 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
557 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
561 if (type == incratom) {
563 * Activate the PropertyNotify events so we receive
564 * when the selection owner does send us the next
567 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
568 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
572 * Deleting the property is the transfer start signal.
574 XDeleteProperty(xw.dpy, xw.win, (int)property);
580 * Line endings are inconsistent in the terminal and GUI world
581 * copy and pasting. When receiving some selection data,
582 * replace all '\n' with '\r'.
583 * FIXME: Fix the computer world.
586 last = data + nitems * format / 8;
587 while ((repl = memchr(repl, '\n', last - repl))) {
591 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
592 ttywrite("\033[200~", 6, 0);
593 ttywrite((char *)data, nitems * format / 8, 1);
594 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
595 ttywrite("\033[201~", 6, 0);
597 /* number of 32-bit chunks returned */
598 ofs += nitems * format / 32;
602 * Deleting the property again tells the selection owner to send the
603 * next data chunk in the property.
605 XDeleteProperty(xw.dpy, xw.win, (int)property);
621 selrequest(XEvent *e)
623 XSelectionRequestEvent *xsre;
625 Atom xa_targets, string, clipboard;
628 xsre = (XSelectionRequestEvent *) e;
629 xev.type = SelectionNotify;
630 xev.requestor = xsre->requestor;
631 xev.selection = xsre->selection;
632 xev.target = xsre->target;
633 xev.time = xsre->time;
634 if (xsre->property == None)
635 xsre->property = xsre->target;
640 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
641 if (xsre->target == xa_targets) {
642 /* respond with the supported type */
643 string = xsel.xtarget;
644 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
645 XA_ATOM, 32, PropModeReplace,
646 (uchar *) &string, 1);
647 xev.property = xsre->property;
648 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
650 * xith XA_STRING non ascii characters may be incorrect in the
651 * requestor. It is not our problem, use utf8.
653 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
654 if (xsre->selection == XA_PRIMARY) {
655 seltext = xsel.primary;
656 } else if (xsre->selection == clipboard) {
657 seltext = xsel.clipboard;
660 "Unhandled clipboard selection 0x%lx\n",
664 if (seltext != NULL) {
665 XChangeProperty(xsre->display, xsre->requestor,
666 xsre->property, xsre->target,
668 (uchar *)seltext, strlen(seltext));
669 xev.property = xsre->property;
673 /* all done, send a notification to the listener */
674 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
675 fprintf(stderr, "Error sending SelectionNotify event\n");
679 setsel(char *str, Time t)
687 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
688 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
695 setsel(str, CurrentTime);
701 int btn = e->xbutton.button;
703 if (1 <= btn && btn <= 11)
704 buttons &= ~(1 << (btn-1));
706 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
711 if (mouseaction(e, 1))
720 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
729 cresize(int width, int height)
738 col = (win.w - 2 * borderpx) / win.cw;
739 row = (win.h - 2 * borderpx) / win.ch;
745 ttyresize(win.tw, win.th);
749 xresize(int col, int row)
751 win.tw = col * win.cw;
752 win.th = row * win.ch;
754 XFreePixmap(xw.dpy, xw.buf);
755 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
756 DefaultDepth(xw.dpy, xw.scr));
757 XftDrawChange(xw.draw, xw.buf);
758 xclear(0, 0, win.w, win.h);
760 /* resize to new width */
761 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
767 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
771 xloadcolor(int i, const char *name, Color *ncolor)
773 XRenderColor color = { .alpha = 0xffff };
776 if (BETWEEN(i, 16, 255)) { /* 256 color */
777 if (i < 6*6*6+16) { /* same colors as xterm */
778 color.red = sixd_to_16bit( ((i-16)/36)%6 );
779 color.green = sixd_to_16bit( ((i-16)/6) %6 );
780 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
781 } else { /* greyscale */
782 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
783 color.green = color.blue = color.red;
785 return XftColorAllocValue(xw.dpy, xw.vis,
786 xw.cmap, &color, ncolor);
791 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
802 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
803 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
805 dc.collen = MAX(LEN(colorname), 256);
806 dc.col = xmalloc(dc.collen * sizeof(Color));
809 for (i = 0; i < dc.collen; i++)
810 if (!xloadcolor(i, NULL, &dc.col[i])) {
812 die("could not allocate color '%s'\n", colorname[i]);
814 die("could not allocate color %d\n", i);
820 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
822 if (!BETWEEN(x, 0, dc.collen - 1))
825 *r = dc.col[x].color.red >> 8;
826 *g = dc.col[x].color.green >> 8;
827 *b = dc.col[x].color.blue >> 8;
833 xsetcolorname(int x, const char *name)
837 if (!BETWEEN(x, 0, dc.collen - 1))
840 if (!xloadcolor(x, name, &ncolor))
843 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
850 * Absolute coordinates.
853 xclear(int x1, int y1, int x2, int y2)
856 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
857 x1, y1, x2-x1, y2-y1);
863 XClassHint class = {opt_name ? opt_name : termname,
864 opt_class ? opt_class : termname};
865 XWMHints wm = {.flags = InputHint, .input = 1};
868 sizeh = XAllocSizeHints();
870 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
871 sizeh->height = win.h;
872 sizeh->width = win.w;
873 sizeh->height_inc = win.ch;
874 sizeh->width_inc = win.cw;
875 sizeh->base_height = 2 * borderpx;
876 sizeh->base_width = 2 * borderpx;
877 sizeh->min_height = win.ch + 2 * borderpx;
878 sizeh->min_width = win.cw + 2 * borderpx;
880 sizeh->flags |= PMaxSize;
881 sizeh->min_width = sizeh->max_width = win.w;
882 sizeh->min_height = sizeh->max_height = win.h;
884 if (xw.gm & (XValue|YValue)) {
885 sizeh->flags |= USPosition | PWinGravity;
888 sizeh->win_gravity = xgeommasktogravity(xw.gm);
891 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
897 xgeommasktogravity(int mask)
899 switch (mask & (XNegative|YNegative)) {
901 return NorthWestGravity;
903 return NorthEastGravity;
905 return SouthWestGravity;
908 return SouthEastGravity;
912 xloadfont(Font *f, FcPattern *pattern)
914 FcPattern *configured;
918 int wantattr, haveattr;
921 * Manually configure instead of calling XftMatchFont
922 * so that we can use the configured pattern for
923 * "missing glyph" lookups.
925 configured = FcPatternDuplicate(pattern);
929 FcConfigSubstitute(NULL, configured, FcMatchPattern);
930 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
932 match = FcFontMatch(NULL, configured, &result);
934 FcPatternDestroy(configured);
938 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
939 FcPatternDestroy(configured);
940 FcPatternDestroy(match);
944 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
947 * Check if xft was unable to find a font with the appropriate
948 * slant but gave us one anyway. Try to mitigate.
950 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
951 &haveattr) != XftResultMatch) || haveattr < wantattr) {
953 fputs("font slant does not match\n", stderr);
957 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
959 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
960 &haveattr) != XftResultMatch) || haveattr != wantattr) {
962 fputs("font weight does not match\n", stderr);
966 XftTextExtentsUtf8(xw.dpy, f->match,
967 (const FcChar8 *) ascii_printable,
968 strlen(ascii_printable), &extents);
971 f->pattern = configured;
973 f->ascent = f->match->ascent;
974 f->descent = f->match->descent;
976 f->rbearing = f->match->max_advance_width;
978 f->height = f->ascent + f->descent;
979 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
985 xloadfonts(const char *fontstr, double fontsize)
990 if (fontstr[0] == '-')
991 pattern = XftXlfdParse(fontstr, False, False);
993 pattern = FcNameParse((const FcChar8 *)fontstr);
996 die("can't open font %s\n", fontstr);
999 FcPatternDel(pattern, FC_PIXEL_SIZE);
1000 FcPatternDel(pattern, FC_SIZE);
1001 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
1002 usedfontsize = fontsize;
1004 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
1006 usedfontsize = fontval;
1007 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
1012 * Default font size is 12, if none given. This is to
1013 * have a known usedfontsize value.
1015 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1018 defaultfontsize = usedfontsize;
1021 if (xloadfont(&dc.font, pattern))
1022 die("can't open font %s\n", fontstr);
1024 if (usedfontsize < 0) {
1025 FcPatternGetDouble(dc.font.match->pattern,
1026 FC_PIXEL_SIZE, 0, &fontval);
1027 usedfontsize = fontval;
1029 defaultfontsize = fontval;
1032 /* Setting character width and height. */
1033 win.cw = ceilf(dc.font.width * cwscale);
1034 win.ch = ceilf(dc.font.height * chscale);
1036 FcPatternDel(pattern, FC_SLANT);
1037 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1038 if (xloadfont(&dc.ifont, pattern))
1039 die("can't open font %s\n", fontstr);
1041 FcPatternDel(pattern, FC_WEIGHT);
1042 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1043 if (xloadfont(&dc.ibfont, pattern))
1044 die("can't open font %s\n", fontstr);
1046 FcPatternDel(pattern, FC_SLANT);
1047 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1048 if (xloadfont(&dc.bfont, pattern))
1049 die("can't open font %s\n", fontstr);
1051 FcPatternDestroy(pattern);
1055 xunloadfont(Font *f)
1057 XftFontClose(xw.dpy, f->match);
1058 FcPatternDestroy(f->pattern);
1060 FcFontSetDestroy(f->set);
1066 /* Free the loaded fonts in the font cache. */
1068 XftFontClose(xw.dpy, frc[--frclen].font);
1070 xunloadfont(&dc.font);
1071 xunloadfont(&dc.bfont);
1072 xunloadfont(&dc.ifont);
1073 xunloadfont(&dc.ibfont);
1077 ximopen(Display *dpy)
1079 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1080 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1082 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1083 if (xw.ime.xim == NULL)
1086 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1087 fprintf(stderr, "XSetIMValues: "
1088 "Could not set XNDestroyCallback.\n");
1090 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1093 if (xw.ime.xic == NULL) {
1094 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1095 XIMPreeditNothing | XIMStatusNothing,
1096 XNClientWindow, xw.win,
1097 XNDestroyCallback, &icdestroy,
1100 if (xw.ime.xic == NULL)
1101 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1107 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1110 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1111 ximinstantiate, NULL);
1115 ximdestroy(XIM xim, XPointer client, XPointer call)
1118 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1119 ximinstantiate, NULL);
1120 XFree(xw.ime.spotlist);
1124 xicdestroy(XIC xim, XPointer client, XPointer call)
1131 xinit(int cols, int rows)
1136 pid_t thispid = getpid();
1137 XColor xmousefg, xmousebg;
1139 if (!(xw.dpy = XOpenDisplay(NULL)))
1140 die("can't open display\n");
1141 xw.scr = XDefaultScreen(xw.dpy);
1142 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1146 die("could not init fontconfig.\n");
1148 usedfont = (opt_font == NULL)? font : opt_font;
1149 xloadfonts(usedfont, 0);
1152 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1155 /* adjust fixed window geometry */
1156 win.w = 2 * borderpx + cols * win.cw;
1157 win.h = 2 * borderpx + rows * win.ch;
1158 if (xw.gm & XNegative)
1159 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1160 if (xw.gm & YNegative)
1161 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1164 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1165 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1166 xw.attrs.bit_gravity = NorthWestGravity;
1167 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1168 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1169 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1170 xw.attrs.colormap = xw.cmap;
1172 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1173 parent = XRootWindow(xw.dpy, xw.scr);
1174 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1175 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1176 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1177 | CWEventMask | CWColormap, &xw.attrs);
1179 memset(&gcvalues, 0, sizeof(gcvalues));
1180 gcvalues.graphics_exposures = False;
1181 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1183 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1184 DefaultDepth(xw.dpy, xw.scr));
1185 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1186 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1188 /* font spec buffer */
1189 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1191 /* Xft rendering context */
1192 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1195 if (!ximopen(xw.dpy)) {
1196 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1197 ximinstantiate, NULL);
1200 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1201 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1202 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1203 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1204 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1206 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1207 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1208 PropModeReplace, (uchar *)&thispid, 1);
1210 win.mode = MODE_NUMLOCK;
1213 XMapWindow(xw.dpy, xw.win);
1214 XSync(xw.dpy, False);
1216 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1217 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1218 xsel.primary = NULL;
1219 xsel.clipboard = NULL;
1220 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1221 if (xsel.xtarget == None)
1222 xsel.xtarget = XA_STRING;
1226 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1228 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1229 ushort mode, prevmode = USHRT_MAX;
1230 Font *font = &dc.font;
1231 int frcflags = FRC_NORMAL;
1232 float runewidth = win.cw;
1236 FcPattern *fcpattern, *fontpattern;
1237 FcFontSet *fcsets[] = { NULL };
1238 FcCharSet *fccharset;
1239 int i, f, numspecs = 0;
1241 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1242 /* Fetch rune and mode for current glyph. */
1244 mode = glyphs[i].mode;
1246 /* Skip dummy wide-character spacing. */
1247 if (mode == ATTR_WDUMMY)
1250 /* Determine font for glyph if different from previous glyph. */
1251 if (prevmode != mode) {
1254 frcflags = FRC_NORMAL;
1255 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1256 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1258 frcflags = FRC_ITALICBOLD;
1259 } else if (mode & ATTR_ITALIC) {
1261 frcflags = FRC_ITALIC;
1262 } else if (mode & ATTR_BOLD) {
1264 frcflags = FRC_BOLD;
1266 yp = winy + font->ascent;
1269 /* Lookup character index with default font. */
1270 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1272 specs[numspecs].font = font->match;
1273 specs[numspecs].glyph = glyphidx;
1274 specs[numspecs].x = (short)xp;
1275 specs[numspecs].y = (short)yp;
1281 /* Fallback on font cache, search the font cache for match. */
1282 for (f = 0; f < frclen; f++) {
1283 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1284 /* Everything correct. */
1285 if (glyphidx && frc[f].flags == frcflags)
1287 /* We got a default font for a not found glyph. */
1288 if (!glyphidx && frc[f].flags == frcflags
1289 && frc[f].unicodep == rune) {
1294 /* Nothing was found. Use fontconfig to find matching font. */
1297 font->set = FcFontSort(0, font->pattern,
1299 fcsets[0] = font->set;
1302 * Nothing was found in the cache. Now use
1303 * some dozen of Fontconfig calls to get the
1304 * font for one single character.
1306 * Xft and fontconfig are design failures.
1308 fcpattern = FcPatternDuplicate(font->pattern);
1309 fccharset = FcCharSetCreate();
1311 FcCharSetAddChar(fccharset, rune);
1312 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1314 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1316 FcConfigSubstitute(0, fcpattern,
1318 FcDefaultSubstitute(fcpattern);
1320 fontpattern = FcFontSetMatch(0, fcsets, 1,
1323 /* Allocate memory for the new cache entry. */
1324 if (frclen >= frccap) {
1326 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1329 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1331 if (!frc[frclen].font)
1332 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1334 frc[frclen].flags = frcflags;
1335 frc[frclen].unicodep = rune;
1337 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1342 FcPatternDestroy(fcpattern);
1343 FcCharSetDestroy(fccharset);
1346 specs[numspecs].font = frc[f].font;
1347 specs[numspecs].glyph = glyphidx;
1348 specs[numspecs].x = (short)xp;
1349 specs[numspecs].y = (short)yp;
1358 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1360 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1361 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1362 width = charlen * win.cw;
1363 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1364 XRenderColor colfg, colbg;
1367 if (base.mode & ATTR_ITALIC) {
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 * chscale + 1,
1478 if (base.mode & ATTR_STRUCK) {
1479 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent * chscale / 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)
1502 /* remove the old cursor */
1503 if (selected(ox, oy))
1504 og.mode ^= ATTR_REVERSE;
1505 xdrawglyph(og, ox, oy);
1507 if (IS_SET(MODE_HIDE))
1511 * Select the right color for the right mode.
1513 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1515 if (IS_SET(MODE_REVERSE)) {
1516 g.mode |= ATTR_REVERSE;
1518 if (selected(cx, cy)) {
1519 drawcol = dc.col[defaultcs];
1522 drawcol = dc.col[defaultrcs];
1526 if (selected(cx, cy)) {
1533 drawcol = dc.col[g.bg];
1536 /* draw the new one */
1537 if (IS_SET(MODE_FOCUSED)) {
1538 switch (win.cursor) {
1539 case 0: /* Blinking block */
1540 case 1: /* Blinking block (default) */
1541 if (IS_SET(MODE_BLINK))
1544 case 2: /* Steady block */
1545 xdrawglyph(g, cx, cy);
1547 case 3: /* Blinking underline */
1548 if (IS_SET(MODE_BLINK))
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 if (IS_SET(MODE_BLINK))
1562 case 6: /* Steady bar */
1563 XftDrawRect(xw.draw, &drawcol,
1564 borderpx + cx * win.cw,
1565 borderpx + cy * win.ch,
1566 cursorthickness, win.ch);
1568 case 7: /* Blinking st cursor */
1569 if (IS_SET(MODE_BLINK))
1572 case 8: /* Steady st cursor */
1573 g.u = 0x2603; /* snowman (U+2603) */
1574 xdrawglyph(g, cx, cy);
1578 XftDrawRect(xw.draw, &drawcol,
1579 borderpx + cx * win.cw,
1580 borderpx + cy * win.ch,
1582 XftDrawRect(xw.draw, &drawcol,
1583 borderpx + cx * win.cw,
1584 borderpx + cy * win.ch,
1586 XftDrawRect(xw.draw, &drawcol,
1587 borderpx + (cx + 1) * win.cw - 1,
1588 borderpx + cy * win.ch,
1590 XftDrawRect(xw.draw, &drawcol,
1591 borderpx + cx * win.cw,
1592 borderpx + (cy + 1) * win.ch - 1,
1600 char buf[sizeof(long) * 8 + 1];
1602 snprintf(buf, sizeof(buf), "%lu", xw.win);
1603 setenv("WINDOWID", buf, 1);
1607 xseticontitle(char *p)
1610 DEFAULT(p, opt_title);
1615 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1618 XSetWMIconName(xw.dpy, xw.win, &prop);
1619 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1627 DEFAULT(p, opt_title);
1632 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1635 XSetWMName(xw.dpy, xw.win, &prop);
1636 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1643 return IS_SET(MODE_VISIBLE);
1647 xdrawline(Line line, int x1, int y1, int x2)
1649 int i, x, ox, numspecs;
1651 XftGlyphFontSpec *specs = xw.specbuf;
1653 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1655 for (x = x1; x < x2 && i < numspecs; x++) {
1657 if (new.mode == ATTR_WDUMMY)
1659 if (selected(x, y1))
1660 new.mode ^= ATTR_REVERSE;
1661 if (i > 0 && ATTRCMP(base, new)) {
1662 xdrawglyphfontspecs(specs, base, i, ox, y1);
1674 xdrawglyphfontspecs(specs, base, i, ox, y1);
1680 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1682 XSetForeground(xw.dpy, dc.gc,
1683 dc.col[IS_SET(MODE_REVERSE)?
1684 defaultfg : defaultbg].pixel);
1688 xximspot(int x, int y)
1690 if (xw.ime.xic == NULL)
1693 xw.ime.spot.x = borderpx + x * win.cw;
1694 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1696 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1706 visibility(XEvent *ev)
1708 XVisibilityEvent *e = &ev->xvisibility;
1710 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1716 win.mode &= ~MODE_VISIBLE;
1720 xsetpointermotion(int set)
1722 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1723 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1727 xsetmode(int set, unsigned int flags)
1729 int mode = win.mode;
1730 MODBIT(win.mode, set, flags);
1731 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1736 xsetcursor(int cursor)
1738 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1740 win.cursor = cursor;
1741 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1742 win.cursor == 3 || win.cursor == 5 ||
1748 xseturgency(int add)
1750 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1752 MODBIT(h->flags, add, XUrgencyHint);
1753 XSetWMHints(xw.dpy, xw.win, h);
1760 if (!(IS_SET(MODE_FOCUSED)))
1763 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1769 XFocusChangeEvent *e = &ev->xfocus;
1771 if (e->mode == NotifyGrab)
1774 if (ev->type == FocusIn) {
1776 XSetICFocus(xw.ime.xic);
1777 win.mode |= MODE_FOCUSED;
1779 if (IS_SET(MODE_FOCUS))
1780 ttywrite("\033[I", 3, 0);
1783 XUnsetICFocus(xw.ime.xic);
1784 win.mode &= ~MODE_FOCUSED;
1785 if (IS_SET(MODE_FOCUS))
1786 ttywrite("\033[O", 3, 0);
1791 match(uint mask, uint state)
1793 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1797 kmap(KeySym k, uint state)
1802 /* Check for mapped keys out of X11 function keys. */
1803 for (i = 0; i < LEN(mappedkeys); i++) {
1804 if (mappedkeys[i] == k)
1807 if (i == LEN(mappedkeys)) {
1808 if ((k & 0xFFFF) < 0xFD00)
1812 for (kp = key; kp < key + LEN(key); kp++) {
1816 if (!match(kp->mask, state))
1819 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1821 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1824 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1836 XKeyEvent *e = &ev->xkey;
1837 KeySym ksym = NoSymbol;
1838 char buf[64], *customkey;
1844 if (IS_SET(MODE_KBDLOCK))
1848 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1849 if (status == XBufferOverflow)
1852 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1855 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1856 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1857 bp->func(&(bp->arg));
1862 /* 2. custom keys from config.h */
1863 if ((customkey = kmap(ksym, e->state))) {
1864 ttywrite(customkey, strlen(customkey), 1);
1868 /* 3. composed string from input method */
1871 if (len == 1 && e->state & Mod1Mask) {
1872 if (IS_SET(MODE_8BIT)) {
1875 len = utf8encode(c, buf);
1883 ttywrite(buf, len, 1);
1891 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1893 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1894 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1895 win.mode |= MODE_FOCUSED;
1897 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1898 win.mode &= ~MODE_FOCUSED;
1900 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1909 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1912 cresize(e->xconfigure.width, e->xconfigure.height);
1919 int w = win.w, h = win.h;
1921 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1922 struct timespec seltv, *tv, now, lastblink, trigger;
1925 /* Waiting for window mapping */
1927 XNextEvent(xw.dpy, &ev);
1929 * This XFilterEvent call is required because of XOpenIM. It
1930 * does filter out the key event and some client message for
1931 * the input method too.
1933 if (XFilterEvent(&ev, None))
1935 if (ev.type == ConfigureNotify) {
1936 w = ev.xconfigure.width;
1937 h = ev.xconfigure.height;
1939 } while (ev.type != MapNotify);
1941 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1944 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1946 FD_SET(ttyfd, &rfd);
1949 if (XPending(xw.dpy))
1950 timeout = 0; /* existing events might not set xfd */
1952 seltv.tv_sec = timeout / 1E3;
1953 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1954 tv = timeout >= 0 ? &seltv : NULL;
1956 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1959 die("select failed: %s\n", strerror(errno));
1961 clock_gettime(CLOCK_MONOTONIC, &now);
1963 if (FD_ISSET(ttyfd, &rfd))
1967 while (XPending(xw.dpy)) {
1969 XNextEvent(xw.dpy, &ev);
1970 if (XFilterEvent(&ev, None))
1972 if (handler[ev.type])
1973 (handler[ev.type])(&ev);
1977 * To reduce flicker and tearing, when new content or event
1978 * triggers drawing, we first wait a bit to ensure we got
1979 * everything, and if nothing new arrives - we draw.
1980 * We start with trying to wait minlatency ms. If more content
1981 * arrives sooner, we retry with shorter and shorter periods,
1982 * and eventually draw even without idle after maxlatency ms.
1983 * Typically this results in low latency while interacting,
1984 * maximum latency intervals during `cat huge.txt`, and perfect
1985 * sync with periodic updates from animations/key-repeats/etc.
1987 if (FD_ISSET(ttyfd, &rfd) || xev) {
1990 if (IS_SET(MODE_BLINK)) {
1991 win.mode ^= MODE_BLINK;
1996 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1997 / maxlatency * minlatency;
1999 continue; /* we have time, try to find idle */
2002 /* idle detected or maxlatency exhausted -> draw */
2004 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
2005 timeout = blinktimeout - TIMEDIFF(now, lastblink);
2007 if (-timeout > blinktimeout) /* start visible */
2008 win.mode |= MODE_BLINK;
2009 win.mode ^= MODE_BLINK;
2010 tsetdirtattr(ATTR_BLINK);
2012 timeout = blinktimeout;
2025 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2026 " [-n name] [-o file]\n"
2027 " [-T title] [-t title] [-w windowid]"
2028 " [[-e] command [args ...]]\n"
2029 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2030 " [-n name] [-o file]\n"
2031 " [-T title] [-t title] [-w windowid] -l line"
2032 " [stty_args ...]\n", argv0, argv0);
2036 main(int argc, char *argv[])
2040 xsetcursor(cursorshape);
2047 opt_class = EARGF(usage());
2054 opt_font = EARGF(usage());
2057 xw.gm = XParseGeometry(EARGF(usage()),
2058 &xw.l, &xw.t, &cols, &rows);
2064 opt_io = EARGF(usage());
2067 opt_line = EARGF(usage());
2070 opt_name = EARGF(usage());
2074 opt_title = EARGF(usage());
2077 opt_embed = EARGF(usage());
2080 die("%s " VERSION "\n", argv0);
2087 if (argc > 0) /* eat all remaining arguments */
2091 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2093 setlocale(LC_CTYPE, "");
2094 XSetLocaleModifiers("");
2095 cols = MAX(cols, 1);
2096 rows = MAX(rows, 1);