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)
1135 Window parent, root;
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 root = XRootWindow(xw.dpy, xw.scr);
1173 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1175 xw.win = XCreateWindow(xw.dpy, root, xw.l, xw.t,
1176 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1177 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1178 | CWEventMask | CWColormap, &xw.attrs);
1180 XReparentWindow(xw.dpy, xw.win, parent, xw.l, xw.t);
1182 memset(&gcvalues, 0, sizeof(gcvalues));
1183 gcvalues.graphics_exposures = False;
1184 dc.gc = XCreateGC(xw.dpy, xw.win, GCGraphicsExposures,
1186 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1187 DefaultDepth(xw.dpy, xw.scr));
1188 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1189 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1191 /* font spec buffer */
1192 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1194 /* Xft rendering context */
1195 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1198 if (!ximopen(xw.dpy)) {
1199 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1200 ximinstantiate, NULL);
1203 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1204 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1205 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1206 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1207 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1209 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1210 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1211 PropModeReplace, (uchar *)&thispid, 1);
1213 win.mode = MODE_NUMLOCK;
1216 XMapWindow(xw.dpy, xw.win);
1217 XSync(xw.dpy, False);
1219 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1220 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1221 xsel.primary = NULL;
1222 xsel.clipboard = NULL;
1223 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1224 if (xsel.xtarget == None)
1225 xsel.xtarget = XA_STRING;
1229 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1231 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1232 ushort mode, prevmode = USHRT_MAX;
1233 Font *font = &dc.font;
1234 int frcflags = FRC_NORMAL;
1235 float runewidth = win.cw;
1239 FcPattern *fcpattern, *fontpattern;
1240 FcFontSet *fcsets[] = { NULL };
1241 FcCharSet *fccharset;
1242 int i, f, numspecs = 0;
1244 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1245 /* Fetch rune and mode for current glyph. */
1247 mode = glyphs[i].mode;
1249 /* Skip dummy wide-character spacing. */
1250 if (mode == ATTR_WDUMMY)
1253 /* Determine font for glyph if different from previous glyph. */
1254 if (prevmode != mode) {
1257 frcflags = FRC_NORMAL;
1258 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1259 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1261 frcflags = FRC_ITALICBOLD;
1262 } else if (mode & ATTR_ITALIC) {
1264 frcflags = FRC_ITALIC;
1265 } else if (mode & ATTR_BOLD) {
1267 frcflags = FRC_BOLD;
1269 yp = winy + font->ascent;
1272 /* Lookup character index with default font. */
1273 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1275 specs[numspecs].font = font->match;
1276 specs[numspecs].glyph = glyphidx;
1277 specs[numspecs].x = (short)xp;
1278 specs[numspecs].y = (short)yp;
1284 /* Fallback on font cache, search the font cache for match. */
1285 for (f = 0; f < frclen; f++) {
1286 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1287 /* Everything correct. */
1288 if (glyphidx && frc[f].flags == frcflags)
1290 /* We got a default font for a not found glyph. */
1291 if (!glyphidx && frc[f].flags == frcflags
1292 && frc[f].unicodep == rune) {
1297 /* Nothing was found. Use fontconfig to find matching font. */
1300 font->set = FcFontSort(0, font->pattern,
1302 fcsets[0] = font->set;
1305 * Nothing was found in the cache. Now use
1306 * some dozen of Fontconfig calls to get the
1307 * font for one single character.
1309 * Xft and fontconfig are design failures.
1311 fcpattern = FcPatternDuplicate(font->pattern);
1312 fccharset = FcCharSetCreate();
1314 FcCharSetAddChar(fccharset, rune);
1315 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1317 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1319 FcConfigSubstitute(0, fcpattern,
1321 FcDefaultSubstitute(fcpattern);
1323 fontpattern = FcFontSetMatch(0, fcsets, 1,
1326 /* Allocate memory for the new cache entry. */
1327 if (frclen >= frccap) {
1329 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1332 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1334 if (!frc[frclen].font)
1335 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1337 frc[frclen].flags = frcflags;
1338 frc[frclen].unicodep = rune;
1340 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1345 FcPatternDestroy(fcpattern);
1346 FcCharSetDestroy(fccharset);
1349 specs[numspecs].font = frc[f].font;
1350 specs[numspecs].glyph = glyphidx;
1351 specs[numspecs].x = (short)xp;
1352 specs[numspecs].y = (short)yp;
1361 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1363 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1364 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1365 width = charlen * win.cw;
1366 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1367 XRenderColor colfg, colbg;
1370 if (base.mode & ATTR_ITALIC) {
1371 base.fg = defaultattr;
1374 if (IS_TRUECOL(base.fg)) {
1375 colfg.alpha = 0xffff;
1376 colfg.red = TRUERED(base.fg);
1377 colfg.green = TRUEGREEN(base.fg);
1378 colfg.blue = TRUEBLUE(base.fg);
1379 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1382 fg = &dc.col[base.fg];
1385 if (IS_TRUECOL(base.bg)) {
1386 colbg.alpha = 0xffff;
1387 colbg.green = TRUEGREEN(base.bg);
1388 colbg.red = TRUERED(base.bg);
1389 colbg.blue = TRUEBLUE(base.bg);
1390 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1393 bg = &dc.col[base.bg];
1396 /* Change basic system colors [0-7] to bright system colors [8-15] */
1397 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1398 fg = &dc.col[base.fg + 8];
1400 if (IS_SET(MODE_REVERSE)) {
1401 if (fg == &dc.col[defaultfg]) {
1402 fg = &dc.col[defaultbg];
1404 colfg.red = ~fg->color.red;
1405 colfg.green = ~fg->color.green;
1406 colfg.blue = ~fg->color.blue;
1407 colfg.alpha = fg->color.alpha;
1408 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1413 if (bg == &dc.col[defaultbg]) {
1414 bg = &dc.col[defaultfg];
1416 colbg.red = ~bg->color.red;
1417 colbg.green = ~bg->color.green;
1418 colbg.blue = ~bg->color.blue;
1419 colbg.alpha = bg->color.alpha;
1420 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1426 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1427 colfg.red = fg->color.red / 2;
1428 colfg.green = fg->color.green / 2;
1429 colfg.blue = fg->color.blue / 2;
1430 colfg.alpha = fg->color.alpha;
1431 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1435 if (base.mode & ATTR_REVERSE) {
1441 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1444 if (base.mode & ATTR_INVISIBLE)
1447 /* Intelligent cleaning up of the borders. */
1449 xclear(0, (y == 0)? 0 : winy, borderpx,
1451 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1453 if (winx + width >= borderpx + win.tw) {
1454 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1455 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1458 xclear(winx, 0, winx + width, borderpx);
1459 if (winy + win.ch >= borderpx + win.th)
1460 xclear(winx, winy + win.ch, winx + width, win.h);
1462 /* Clean up the region we want to draw to. */
1463 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1465 /* Set the clip region because Xft is sometimes dirty. */
1470 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1472 /* Render the glyphs. */
1473 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1475 /* Render underline and strikethrough. */
1476 if (base.mode & ATTR_UNDERLINE) {
1477 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent * chscale + 1,
1481 if (base.mode & ATTR_STRUCK) {
1482 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent * chscale / 3,
1486 /* Reset clip to none. */
1487 XftDrawSetClip(xw.draw, 0);
1491 xdrawglyph(Glyph g, int x, int y)
1494 XftGlyphFontSpec spec;
1496 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1497 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1501 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1505 /* remove the old cursor */
1506 if (selected(ox, oy))
1507 og.mode ^= ATTR_REVERSE;
1508 xdrawglyph(og, ox, oy);
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 0: /* Blinking block */
1543 case 1: /* Blinking block (default) */
1544 if (IS_SET(MODE_BLINK))
1547 case 2: /* Steady block */
1548 xdrawglyph(g, cx, cy);
1550 case 3: /* Blinking underline */
1551 if (IS_SET(MODE_BLINK))
1554 case 4: /* Steady underline */
1555 XftDrawRect(xw.draw, &drawcol,
1556 borderpx + cx * win.cw,
1557 borderpx + (cy + 1) * win.ch - \
1559 win.cw, cursorthickness);
1561 case 5: /* Blinking bar */
1562 if (IS_SET(MODE_BLINK))
1565 case 6: /* Steady bar */
1566 XftDrawRect(xw.draw, &drawcol,
1567 borderpx + cx * win.cw,
1568 borderpx + cy * win.ch,
1569 cursorthickness, win.ch);
1571 case 7: /* Blinking st cursor */
1572 if (IS_SET(MODE_BLINK))
1575 case 8: /* Steady st cursor */
1576 g.u = 0x2603; /* snowman (U+2603) */
1577 xdrawglyph(g, cx, cy);
1581 XftDrawRect(xw.draw, &drawcol,
1582 borderpx + cx * win.cw,
1583 borderpx + cy * win.ch,
1585 XftDrawRect(xw.draw, &drawcol,
1586 borderpx + cx * win.cw,
1587 borderpx + cy * win.ch,
1589 XftDrawRect(xw.draw, &drawcol,
1590 borderpx + (cx + 1) * win.cw - 1,
1591 borderpx + cy * win.ch,
1593 XftDrawRect(xw.draw, &drawcol,
1594 borderpx + cx * win.cw,
1595 borderpx + (cy + 1) * win.ch - 1,
1603 char buf[sizeof(long) * 8 + 1];
1605 snprintf(buf, sizeof(buf), "%lu", xw.win);
1606 setenv("WINDOWID", buf, 1);
1610 xseticontitle(char *p)
1613 DEFAULT(p, opt_title);
1618 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1621 XSetWMIconName(xw.dpy, xw.win, &prop);
1622 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1630 DEFAULT(p, opt_title);
1635 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1638 XSetWMName(xw.dpy, xw.win, &prop);
1639 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1646 return IS_SET(MODE_VISIBLE);
1650 xdrawline(Line line, int x1, int y1, int x2)
1652 int i, x, ox, numspecs;
1654 XftGlyphFontSpec *specs = xw.specbuf;
1656 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1658 for (x = x1; x < x2 && i < numspecs; x++) {
1660 if (new.mode == ATTR_WDUMMY)
1662 if (selected(x, y1))
1663 new.mode ^= ATTR_REVERSE;
1664 if (i > 0 && ATTRCMP(base, new)) {
1665 xdrawglyphfontspecs(specs, base, i, ox, y1);
1677 xdrawglyphfontspecs(specs, base, i, ox, y1);
1683 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1685 XSetForeground(xw.dpy, dc.gc,
1686 dc.col[IS_SET(MODE_REVERSE)?
1687 defaultfg : defaultbg].pixel);
1691 xximspot(int x, int y)
1693 if (xw.ime.xic == NULL)
1696 xw.ime.spot.x = borderpx + x * win.cw;
1697 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1699 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1709 visibility(XEvent *ev)
1711 XVisibilityEvent *e = &ev->xvisibility;
1713 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1719 win.mode &= ~MODE_VISIBLE;
1723 xsetpointermotion(int set)
1725 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1726 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1730 xsetmode(int set, unsigned int flags)
1732 int mode = win.mode;
1733 MODBIT(win.mode, set, flags);
1734 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1739 xsetcursor(int cursor)
1741 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1743 win.cursor = cursor;
1744 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1745 win.cursor == 3 || win.cursor == 5 ||
1751 xseturgency(int add)
1753 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1755 MODBIT(h->flags, add, XUrgencyHint);
1756 XSetWMHints(xw.dpy, xw.win, h);
1763 if (!(IS_SET(MODE_FOCUSED)))
1766 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1772 XFocusChangeEvent *e = &ev->xfocus;
1774 if (e->mode == NotifyGrab)
1777 if (ev->type == FocusIn) {
1779 XSetICFocus(xw.ime.xic);
1780 win.mode |= MODE_FOCUSED;
1782 if (IS_SET(MODE_FOCUS))
1783 ttywrite("\033[I", 3, 0);
1786 XUnsetICFocus(xw.ime.xic);
1787 win.mode &= ~MODE_FOCUSED;
1788 if (IS_SET(MODE_FOCUS))
1789 ttywrite("\033[O", 3, 0);
1794 match(uint mask, uint state)
1796 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1800 kmap(KeySym k, uint state)
1805 /* Check for mapped keys out of X11 function keys. */
1806 for (i = 0; i < LEN(mappedkeys); i++) {
1807 if (mappedkeys[i] == k)
1810 if (i == LEN(mappedkeys)) {
1811 if ((k & 0xFFFF) < 0xFD00)
1815 for (kp = key; kp < key + LEN(key); kp++) {
1819 if (!match(kp->mask, state))
1822 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1824 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1827 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1839 XKeyEvent *e = &ev->xkey;
1840 KeySym ksym = NoSymbol;
1841 char buf[64], *customkey;
1847 if (IS_SET(MODE_KBDLOCK))
1851 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1852 if (status == XBufferOverflow)
1855 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1858 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1859 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1860 bp->func(&(bp->arg));
1865 /* 2. custom keys from config.h */
1866 if ((customkey = kmap(ksym, e->state))) {
1867 ttywrite(customkey, strlen(customkey), 1);
1871 /* 3. composed string from input method */
1874 if (len == 1 && e->state & Mod1Mask) {
1875 if (IS_SET(MODE_8BIT)) {
1878 len = utf8encode(c, buf);
1886 ttywrite(buf, len, 1);
1894 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1896 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1897 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1898 win.mode |= MODE_FOCUSED;
1900 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1901 win.mode &= ~MODE_FOCUSED;
1903 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1912 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1915 cresize(e->xconfigure.width, e->xconfigure.height);
1922 int w = win.w, h = win.h;
1924 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1925 struct timespec seltv, *tv, now, lastblink, trigger;
1928 /* Waiting for window mapping */
1930 XNextEvent(xw.dpy, &ev);
1932 * This XFilterEvent call is required because of XOpenIM. It
1933 * does filter out the key event and some client message for
1934 * the input method too.
1936 if (XFilterEvent(&ev, None))
1938 if (ev.type == ConfigureNotify) {
1939 w = ev.xconfigure.width;
1940 h = ev.xconfigure.height;
1942 } while (ev.type != MapNotify);
1944 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1947 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1949 FD_SET(ttyfd, &rfd);
1952 if (XPending(xw.dpy))
1953 timeout = 0; /* existing events might not set xfd */
1955 seltv.tv_sec = timeout / 1E3;
1956 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1957 tv = timeout >= 0 ? &seltv : NULL;
1959 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1962 die("select failed: %s\n", strerror(errno));
1964 clock_gettime(CLOCK_MONOTONIC, &now);
1966 if (FD_ISSET(ttyfd, &rfd))
1970 while (XPending(xw.dpy)) {
1972 XNextEvent(xw.dpy, &ev);
1973 if (XFilterEvent(&ev, None))
1975 if (handler[ev.type])
1976 (handler[ev.type])(&ev);
1980 * To reduce flicker and tearing, when new content or event
1981 * triggers drawing, we first wait a bit to ensure we got
1982 * everything, and if nothing new arrives - we draw.
1983 * We start with trying to wait minlatency ms. If more content
1984 * arrives sooner, we retry with shorter and shorter periods,
1985 * and eventually draw even without idle after maxlatency ms.
1986 * Typically this results in low latency while interacting,
1987 * maximum latency intervals during `cat huge.txt`, and perfect
1988 * sync with periodic updates from animations/key-repeats/etc.
1990 if (FD_ISSET(ttyfd, &rfd) || xev) {
1993 if (IS_SET(MODE_BLINK)) {
1994 win.mode ^= MODE_BLINK;
1999 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
2000 / maxlatency * minlatency;
2002 continue; /* we have time, try to find idle */
2005 /* idle detected or maxlatency exhausted -> draw */
2007 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
2008 timeout = blinktimeout - TIMEDIFF(now, lastblink);
2010 if (-timeout > blinktimeout) /* start visible */
2011 win.mode |= MODE_BLINK;
2012 win.mode ^= MODE_BLINK;
2013 tsetdirtattr(ATTR_BLINK);
2015 timeout = blinktimeout;
2028 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2029 " [-n name] [-o file]\n"
2030 " [-T title] [-t title] [-w windowid]"
2031 " [[-e] command [args ...]]\n"
2032 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2033 " [-n name] [-o file]\n"
2034 " [-T title] [-t title] [-w windowid] -l line"
2035 " [stty_args ...]\n", argv0, argv0);
2039 main(int argc, char *argv[])
2043 xsetcursor(cursorshape);
2050 opt_class = EARGF(usage());
2057 opt_font = EARGF(usage());
2060 xw.gm = XParseGeometry(EARGF(usage()),
2061 &xw.l, &xw.t, &cols, &rows);
2067 opt_io = EARGF(usage());
2070 opt_line = EARGF(usage());
2073 opt_name = EARGF(usage());
2077 opt_title = EARGF(usage());
2080 opt_embed = EARGF(usage());
2083 die("%s " VERSION "\n", argv0);
2090 if (argc > 0) /* eat all remaining arguments */
2094 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2096 setlocale(LC_CTYPE, "");
2097 XSetLocaleModifiers("");
2098 cols = MAX(cols, 1);
2099 rows = MAX(rows, 1);