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 */
257 static int cursorblinks = 0;
260 clipcopy(const Arg *dummy)
264 free(xsel.clipboard);
265 xsel.clipboard = NULL;
267 if (xsel.primary != NULL) {
268 xsel.clipboard = xstrdup(xsel.primary);
269 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
270 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
275 clippaste(const Arg *dummy)
279 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
280 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
281 xw.win, CurrentTime);
285 selpaste(const Arg *dummy)
287 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
288 xw.win, CurrentTime);
292 numlock(const Arg *dummy)
294 win.mode ^= MODE_NUMLOCK;
302 larg.f = usedfontsize + arg->f;
307 zoomabs(const Arg *arg)
310 xloadfonts(usedfont, arg->f);
317 zoomreset(const Arg *arg)
321 if (defaultfontsize > 0) {
322 larg.f = defaultfontsize;
328 ttysend(const Arg *arg)
330 ttywrite(arg->s, strlen(arg->s), 1);
336 int x = e->xbutton.x - borderpx;
337 LIMIT(x, 0, win.tw - 1);
344 int y = e->xbutton.y - borderpx;
345 LIMIT(y, 0, win.th - 1);
350 mousesel(XEvent *e, int done)
352 int type, seltype = SEL_REGULAR;
353 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
355 for (type = 1; type < LEN(selmasks); ++type) {
356 if (match(selmasks[type], state)) {
361 selextend(evcol(e), evrow(e), seltype, done);
363 setsel(getsel(), e->xbutton.time);
367 mousereport(XEvent *e)
369 int len, x = evcol(e), y = evrow(e),
370 button = e->xbutton.button, state = e->xbutton.state;
375 if (e->xbutton.type == MotionNotify) {
376 if (x == ox && y == oy)
378 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
380 /* MOUSE_MOTION: no reporting if no button is pressed */
381 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
384 button = oldbutton + 32;
388 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
394 else if (button >= 3)
397 if (e->xbutton.type == ButtonPress) {
401 } else if (e->xbutton.type == ButtonRelease) {
403 /* MODE_MOUSEX10: no button release reporting */
404 if (IS_SET(MODE_MOUSEX10))
406 if (button == 64 || button == 65)
411 if (!IS_SET(MODE_MOUSEX10)) {
412 button += ((state & ShiftMask ) ? 4 : 0)
413 + ((state & Mod4Mask ) ? 8 : 0)
414 + ((state & ControlMask) ? 16 : 0);
417 if (IS_SET(MODE_MOUSESGR)) {
418 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
420 e->xbutton.type == ButtonRelease ? 'm' : 'M');
421 } else if (x < 223 && y < 223) {
422 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
423 32+button, 32+x+1, 32+y+1);
428 ttywrite(buf, len, 0);
432 buttonmask(uint button)
434 return button == Button1 ? Button1Mask
435 : button == Button2 ? Button2Mask
436 : button == Button3 ? Button3Mask
437 : button == Button4 ? Button4Mask
438 : button == Button5 ? Button5Mask
443 mouseaction(XEvent *e, uint release)
447 /* ignore Button<N>mask for Button<N> - it's set on release */
448 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
450 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
451 if (ms->release == release &&
452 ms->button == e->xbutton.button &&
453 (match(ms->mod, state) || /* exact or forced */
454 match(ms->mod, state & ~forcemousemod))) {
455 ms->func(&(ms->arg));
469 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
474 if (mouseaction(e, 0))
477 if (e->xbutton.button == Button1) {
479 * If the user clicks below predefined timeouts specific
480 * snapping behaviour is exposed.
482 clock_gettime(CLOCK_MONOTONIC, &now);
483 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
485 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
490 xsel.tclick2 = xsel.tclick1;
493 selstart(evcol(e), evrow(e), snap);
498 propnotify(XEvent *e)
500 XPropertyEvent *xpev;
501 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
503 xpev = &e->xproperty;
504 if (xpev->state == PropertyNewValue &&
505 (xpev->atom == XA_PRIMARY ||
506 xpev->atom == clipboard)) {
514 ulong nitems, ofs, rem;
516 uchar *data, *last, *repl;
517 Atom type, incratom, property = None;
519 incratom = XInternAtom(xw.dpy, "INCR", 0);
522 if (e->type == SelectionNotify)
523 property = e->xselection.property;
524 else if (e->type == PropertyNotify)
525 property = e->xproperty.atom;
527 if (property == None)
531 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
532 BUFSIZ/4, False, AnyPropertyType,
533 &type, &format, &nitems, &rem,
535 fprintf(stderr, "Clipboard allocation failed\n");
539 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
541 * If there is some PropertyNotify with no data, then
542 * this is the signal of the selection owner that all
543 * data has been transferred. We won't need to receive
544 * PropertyNotify events anymore.
546 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
547 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
551 if (type == incratom) {
553 * Activate the PropertyNotify events so we receive
554 * when the selection owner does send us the next
557 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
558 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
562 * Deleting the property is the transfer start signal.
564 XDeleteProperty(xw.dpy, xw.win, (int)property);
570 * Line endings are inconsistent in the terminal and GUI world
571 * copy and pasting. When receiving some selection data,
572 * replace all '\n' with '\r'.
573 * FIXME: Fix the computer world.
576 last = data + nitems * format / 8;
577 while ((repl = memchr(repl, '\n', last - repl))) {
581 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
582 ttywrite("\033[200~", 6, 0);
583 ttywrite((char *)data, nitems * format / 8, 1);
584 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
585 ttywrite("\033[201~", 6, 0);
587 /* number of 32-bit chunks returned */
588 ofs += nitems * format / 32;
592 * Deleting the property again tells the selection owner to send the
593 * next data chunk in the property.
595 XDeleteProperty(xw.dpy, xw.win, (int)property);
611 selrequest(XEvent *e)
613 XSelectionRequestEvent *xsre;
615 Atom xa_targets, string, clipboard;
618 xsre = (XSelectionRequestEvent *) e;
619 xev.type = SelectionNotify;
620 xev.requestor = xsre->requestor;
621 xev.selection = xsre->selection;
622 xev.target = xsre->target;
623 xev.time = xsre->time;
624 if (xsre->property == None)
625 xsre->property = xsre->target;
630 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
631 if (xsre->target == xa_targets) {
632 /* respond with the supported type */
633 string = xsel.xtarget;
634 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
635 XA_ATOM, 32, PropModeReplace,
636 (uchar *) &string, 1);
637 xev.property = xsre->property;
638 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
640 * xith XA_STRING non ascii characters may be incorrect in the
641 * requestor. It is not our problem, use utf8.
643 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
644 if (xsre->selection == XA_PRIMARY) {
645 seltext = xsel.primary;
646 } else if (xsre->selection == clipboard) {
647 seltext = xsel.clipboard;
650 "Unhandled clipboard selection 0x%lx\n",
654 if (seltext != NULL) {
655 XChangeProperty(xsre->display, xsre->requestor,
656 xsre->property, xsre->target,
658 (uchar *)seltext, strlen(seltext));
659 xev.property = xsre->property;
663 /* all done, send a notification to the listener */
664 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
665 fprintf(stderr, "Error sending SelectionNotify event\n");
669 setsel(char *str, Time t)
677 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
678 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
685 setsel(str, CurrentTime);
691 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
696 if (mouseaction(e, 1))
698 if (e->xbutton.button == Button1)
705 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
714 cresize(int width, int height)
723 col = (win.w - 2 * borderpx) / win.cw;
724 row = (win.h - 2 * borderpx) / win.ch;
730 ttyresize(win.tw, win.th);
734 xresize(int col, int row)
736 win.tw = col * win.cw;
737 win.th = row * win.ch;
739 XFreePixmap(xw.dpy, xw.buf);
740 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
741 DefaultDepth(xw.dpy, xw.scr));
742 XftDrawChange(xw.draw, xw.buf);
743 xclear(0, 0, win.w, win.h);
745 /* resize to new width */
746 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
752 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
756 xloadcolor(int i, const char *name, Color *ncolor)
758 XRenderColor color = { .alpha = 0xffff };
761 if (BETWEEN(i, 16, 255)) { /* 256 color */
762 if (i < 6*6*6+16) { /* same colors as xterm */
763 color.red = sixd_to_16bit( ((i-16)/36)%6 );
764 color.green = sixd_to_16bit( ((i-16)/6) %6 );
765 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
766 } else { /* greyscale */
767 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
768 color.green = color.blue = color.red;
770 return XftColorAllocValue(xw.dpy, xw.vis,
771 xw.cmap, &color, ncolor);
776 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
787 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
788 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
790 dc.collen = MAX(LEN(colorname), 256);
791 dc.col = xmalloc(dc.collen * sizeof(Color));
794 for (i = 0; i < dc.collen; i++)
795 if (!xloadcolor(i, NULL, &dc.col[i])) {
797 die("could not allocate color '%s'\n", colorname[i]);
799 die("could not allocate color %d\n", i);
805 xsetcolorname(int x, const char *name)
809 if (!BETWEEN(x, 0, dc.collen))
812 if (!xloadcolor(x, name, &ncolor))
815 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
822 * Absolute coordinates.
825 xclear(int x1, int y1, int x2, int y2)
828 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
829 x1, y1, x2-x1, y2-y1);
835 XClassHint class = {opt_name ? opt_name : termname,
836 opt_class ? opt_class : termname};
837 XWMHints wm = {.flags = InputHint, .input = 1};
840 sizeh = XAllocSizeHints();
842 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
843 sizeh->height = win.h;
844 sizeh->width = win.w;
845 sizeh->height_inc = win.ch;
846 sizeh->width_inc = win.cw;
847 sizeh->base_height = 2 * borderpx;
848 sizeh->base_width = 2 * borderpx;
849 sizeh->min_height = win.ch + 2 * borderpx;
850 sizeh->min_width = win.cw + 2 * borderpx;
852 sizeh->flags |= PMaxSize;
853 sizeh->min_width = sizeh->max_width = win.w;
854 sizeh->min_height = sizeh->max_height = win.h;
856 if (xw.gm & (XValue|YValue)) {
857 sizeh->flags |= USPosition | PWinGravity;
860 sizeh->win_gravity = xgeommasktogravity(xw.gm);
863 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
869 xgeommasktogravity(int mask)
871 switch (mask & (XNegative|YNegative)) {
873 return NorthWestGravity;
875 return NorthEastGravity;
877 return SouthWestGravity;
880 return SouthEastGravity;
884 xloadfont(Font *f, FcPattern *pattern)
886 FcPattern *configured;
890 int wantattr, haveattr;
893 * Manually configure instead of calling XftMatchFont
894 * so that we can use the configured pattern for
895 * "missing glyph" lookups.
897 configured = FcPatternDuplicate(pattern);
901 FcConfigSubstitute(NULL, configured, FcMatchPattern);
902 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
904 match = FcFontMatch(NULL, configured, &result);
906 FcPatternDestroy(configured);
910 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
911 FcPatternDestroy(configured);
912 FcPatternDestroy(match);
916 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
919 * Check if xft was unable to find a font with the appropriate
920 * slant but gave us one anyway. Try to mitigate.
922 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
923 &haveattr) != XftResultMatch) || haveattr < wantattr) {
925 fputs("font slant does not match\n", stderr);
929 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
931 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
932 &haveattr) != XftResultMatch) || haveattr != wantattr) {
934 fputs("font weight does not match\n", stderr);
938 XftTextExtentsUtf8(xw.dpy, f->match,
939 (const FcChar8 *) ascii_printable,
940 strlen(ascii_printable), &extents);
943 f->pattern = configured;
945 f->ascent = f->match->ascent;
946 f->descent = f->match->descent;
948 f->rbearing = f->match->max_advance_width;
950 f->height = f->ascent + f->descent;
951 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
957 xloadfonts(const char *fontstr, double fontsize)
962 if (fontstr[0] == '-')
963 pattern = XftXlfdParse(fontstr, False, False);
965 pattern = FcNameParse((const FcChar8 *)fontstr);
968 die("can't open font %s\n", fontstr);
971 FcPatternDel(pattern, FC_PIXEL_SIZE);
972 FcPatternDel(pattern, FC_SIZE);
973 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
974 usedfontsize = fontsize;
976 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
978 usedfontsize = fontval;
979 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
984 * Default font size is 12, if none given. This is to
985 * have a known usedfontsize value.
987 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
990 defaultfontsize = usedfontsize;
993 if (xloadfont(&dc.font, pattern))
994 die("can't open font %s\n", fontstr);
996 if (usedfontsize < 0) {
997 FcPatternGetDouble(dc.font.match->pattern,
998 FC_PIXEL_SIZE, 0, &fontval);
999 usedfontsize = fontval;
1001 defaultfontsize = fontval;
1004 /* Setting character width and height. */
1005 win.cw = ceilf(dc.font.width * cwscale);
1006 win.ch = ceilf(dc.font.height * chscale);
1008 FcPatternDel(pattern, FC_SLANT);
1009 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1010 if (xloadfont(&dc.ifont, pattern))
1011 die("can't open font %s\n", fontstr);
1013 FcPatternDel(pattern, FC_WEIGHT);
1014 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1015 if (xloadfont(&dc.ibfont, pattern))
1016 die("can't open font %s\n", fontstr);
1018 FcPatternDel(pattern, FC_SLANT);
1019 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1020 if (xloadfont(&dc.bfont, pattern))
1021 die("can't open font %s\n", fontstr);
1023 FcPatternDestroy(pattern);
1027 xunloadfont(Font *f)
1029 XftFontClose(xw.dpy, f->match);
1030 FcPatternDestroy(f->pattern);
1032 FcFontSetDestroy(f->set);
1038 /* Clear Harfbuzz font cache. */
1041 /* Free the loaded fonts in the font cache. */
1043 XftFontClose(xw.dpy, frc[--frclen].font);
1045 xunloadfont(&dc.font);
1046 xunloadfont(&dc.bfont);
1047 xunloadfont(&dc.ifont);
1048 xunloadfont(&dc.ibfont);
1052 ximopen(Display *dpy)
1054 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1055 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1057 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1058 if (xw.ime.xim == NULL)
1061 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1062 fprintf(stderr, "XSetIMValues: "
1063 "Could not set XNDestroyCallback.\n");
1065 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1068 if (xw.ime.xic == NULL) {
1069 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1070 XIMPreeditNothing | XIMStatusNothing,
1071 XNClientWindow, xw.win,
1072 XNDestroyCallback, &icdestroy,
1075 if (xw.ime.xic == NULL)
1076 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1082 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1085 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1086 ximinstantiate, NULL);
1090 ximdestroy(XIM xim, XPointer client, XPointer call)
1093 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1094 ximinstantiate, NULL);
1095 XFree(xw.ime.spotlist);
1099 xicdestroy(XIC xim, XPointer client, XPointer call)
1106 xinit(int cols, int rows)
1111 pid_t thispid = getpid();
1112 XColor xmousefg, xmousebg;
1114 if (!(xw.dpy = XOpenDisplay(NULL)))
1115 die("can't open display\n");
1116 xw.scr = XDefaultScreen(xw.dpy);
1117 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1121 die("could not init fontconfig.\n");
1123 usedfont = (opt_font == NULL)? font : opt_font;
1124 xloadfonts(usedfont, 0);
1127 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1130 /* adjust fixed window geometry */
1131 win.w = 2 * borderpx + cols * win.cw;
1132 win.h = 2 * borderpx + rows * win.ch;
1133 if (xw.gm & XNegative)
1134 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1135 if (xw.gm & YNegative)
1136 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1139 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1140 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1141 xw.attrs.bit_gravity = NorthWestGravity;
1142 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1143 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1144 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1145 xw.attrs.colormap = xw.cmap;
1147 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1148 parent = XRootWindow(xw.dpy, xw.scr);
1149 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1150 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1151 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1152 | CWEventMask | CWColormap, &xw.attrs);
1154 memset(&gcvalues, 0, sizeof(gcvalues));
1155 gcvalues.graphics_exposures = False;
1156 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1158 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1159 DefaultDepth(xw.dpy, xw.scr));
1160 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1161 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1163 /* font spec buffer */
1164 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1166 /* Xft rendering context */
1167 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1170 if (!ximopen(xw.dpy)) {
1171 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1172 ximinstantiate, NULL);
1175 /* white cursor, black outline */
1176 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1177 XDefineCursor(xw.dpy, xw.win, cursor);
1179 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1180 xmousefg.red = 0xffff;
1181 xmousefg.green = 0xffff;
1182 xmousefg.blue = 0xffff;
1185 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1186 xmousebg.red = 0x0000;
1187 xmousebg.green = 0x0000;
1188 xmousebg.blue = 0x0000;
1191 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1193 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1194 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1195 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1196 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1197 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1199 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1200 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1201 PropModeReplace, (uchar *)&thispid, 1);
1203 win.mode = MODE_NUMLOCK;
1206 XMapWindow(xw.dpy, xw.win);
1207 XSync(xw.dpy, False);
1209 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1210 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1211 xsel.primary = NULL;
1212 xsel.clipboard = NULL;
1213 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1214 if (xsel.xtarget == None)
1215 xsel.xtarget = XA_STRING;
1219 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1221 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1222 ushort mode, prevmode = USHRT_MAX;
1223 Font *font = &dc.font;
1224 int frcflags = FRC_NORMAL;
1225 float runewidth = win.cw;
1229 FcPattern *fcpattern, *fontpattern;
1230 FcFontSet *fcsets[] = { NULL };
1231 FcCharSet *fccharset;
1232 int i, f, numspecs = 0;
1234 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1235 /* Fetch rune and mode for current glyph. */
1237 mode = glyphs[i].mode;
1239 /* Skip dummy wide-character spacing. */
1240 if (mode & ATTR_WDUMMY)
1243 /* Determine font for glyph if different from previous glyph. */
1244 if (prevmode != mode) {
1247 frcflags = FRC_NORMAL;
1248 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1249 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1251 frcflags = FRC_ITALICBOLD;
1252 } else if (mode & ATTR_ITALIC) {
1254 frcflags = FRC_ITALIC;
1255 } else if (mode & ATTR_BOLD) {
1257 frcflags = FRC_BOLD;
1259 yp = winy + font->ascent;
1262 /* Lookup character index with default font. */
1263 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1265 specs[numspecs].font = font->match;
1266 specs[numspecs].glyph = glyphidx;
1267 specs[numspecs].x = (short)xp;
1268 specs[numspecs].y = (short)yp;
1274 /* Fallback on font cache, search the font cache for match. */
1275 for (f = 0; f < frclen; f++) {
1276 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1277 /* Everything correct. */
1278 if (glyphidx && frc[f].flags == frcflags)
1280 /* We got a default font for a not found glyph. */
1281 if (!glyphidx && frc[f].flags == frcflags
1282 && frc[f].unicodep == rune) {
1287 /* Nothing was found. Use fontconfig to find matching font. */
1290 font->set = FcFontSort(0, font->pattern,
1292 fcsets[0] = font->set;
1295 * Nothing was found in the cache. Now use
1296 * some dozen of Fontconfig calls to get the
1297 * font for one single character.
1299 * Xft and fontconfig are design failures.
1301 fcpattern = FcPatternDuplicate(font->pattern);
1302 fccharset = FcCharSetCreate();
1304 FcCharSetAddChar(fccharset, rune);
1305 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1307 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1309 FcConfigSubstitute(0, fcpattern,
1311 FcDefaultSubstitute(fcpattern);
1313 fontpattern = FcFontSetMatch(0, fcsets, 1,
1316 /* Allocate memory for the new cache entry. */
1317 if (frclen >= frccap) {
1319 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1322 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1324 if (!frc[frclen].font)
1325 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1327 frc[frclen].flags = frcflags;
1328 frc[frclen].unicodep = rune;
1330 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1335 FcPatternDestroy(fcpattern);
1336 FcCharSetDestroy(fccharset);
1339 specs[numspecs].font = frc[f].font;
1340 specs[numspecs].glyph = glyphidx;
1341 specs[numspecs].x = (short)xp;
1342 specs[numspecs].y = (short)yp;
1347 /* Harfbuzz transformation for ligatures. */
1348 hbtransform(specs, glyphs, len, x, y);
1354 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1356 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1357 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1358 width = charlen * win.cw;
1359 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1360 XRenderColor colfg, colbg;
1363 /* Fallback on color display for attributes not supported by the font */
1364 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1365 if (dc.ibfont.badslant || dc.ibfont.badweight)
1366 base.fg = defaultattr;
1367 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1368 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1369 base.fg = defaultattr;
1372 if (IS_TRUECOL(base.fg)) {
1373 colfg.alpha = 0xffff;
1374 colfg.red = TRUERED(base.fg);
1375 colfg.green = TRUEGREEN(base.fg);
1376 colfg.blue = TRUEBLUE(base.fg);
1377 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1380 fg = &dc.col[base.fg];
1383 if (IS_TRUECOL(base.bg)) {
1384 colbg.alpha = 0xffff;
1385 colbg.green = TRUEGREEN(base.bg);
1386 colbg.red = TRUERED(base.bg);
1387 colbg.blue = TRUEBLUE(base.bg);
1388 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1391 bg = &dc.col[base.bg];
1394 /* Change basic system colors [0-7] to bright system colors [8-15] */
1395 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1396 fg = &dc.col[base.fg + 8];
1398 if (IS_SET(MODE_REVERSE)) {
1399 if (fg == &dc.col[defaultfg]) {
1400 fg = &dc.col[defaultbg];
1402 colfg.red = ~fg->color.red;
1403 colfg.green = ~fg->color.green;
1404 colfg.blue = ~fg->color.blue;
1405 colfg.alpha = fg->color.alpha;
1406 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1411 if (bg == &dc.col[defaultbg]) {
1412 bg = &dc.col[defaultfg];
1414 colbg.red = ~bg->color.red;
1415 colbg.green = ~bg->color.green;
1416 colbg.blue = ~bg->color.blue;
1417 colbg.alpha = bg->color.alpha;
1418 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1424 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1425 colfg.red = fg->color.red / 2;
1426 colfg.green = fg->color.green / 2;
1427 colfg.blue = fg->color.blue / 2;
1428 colfg.alpha = fg->color.alpha;
1429 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1433 if (base.mode & ATTR_REVERSE) {
1439 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1442 if (base.mode & ATTR_INVISIBLE)
1445 /* Intelligent cleaning up of the borders. */
1447 xclear(0, (y == 0)? 0 : winy, borderpx,
1449 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1451 if (winx + width >= borderpx + win.tw) {
1452 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1453 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1456 xclear(winx, 0, winx + width, borderpx);
1457 if (winy + win.ch >= borderpx + win.th)
1458 xclear(winx, winy + win.ch, winx + width, win.h);
1460 /* Clean up the region we want to draw to. */
1461 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1463 /* Set the clip region because Xft is sometimes dirty. */
1468 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1470 /* Render the glyphs. */
1471 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1473 /* Render underline and strikethrough. */
1474 if (base.mode & ATTR_UNDERLINE) {
1475 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1479 if (base.mode & ATTR_STRUCK) {
1480 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1484 /* Reset clip to none. */
1485 XftDrawSetClip(xw.draw, 0);
1489 xdrawglyph(Glyph g, int x, int y)
1492 XftGlyphFontSpec spec;
1494 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1495 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1499 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og, Line line, int len)
1503 /* remove the old cursor */
1504 if (selected(ox, oy))
1505 og.mode ^= ATTR_REVERSE;
1507 /* Redraw the line where cursor was previously.
1508 * It will restore the ligatures broken by the cursor. */
1509 xdrawline(line, 0, oy, len);
1511 if (IS_SET(MODE_HIDE))
1515 * Select the right color for the right mode.
1517 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1519 if (IS_SET(MODE_REVERSE)) {
1520 g.mode |= ATTR_REVERSE;
1522 if (selected(cx, cy)) {
1523 drawcol = dc.col[defaultcs];
1526 drawcol = dc.col[defaultrcs];
1530 if (selected(cx, cy)) {
1537 drawcol = dc.col[g.bg];
1540 /* draw the new one */
1541 if (IS_SET(MODE_FOCUSED)) {
1542 switch (win.cursor) {
1543 case 0: /* Blinking block */
1544 case 1: /* Blinking block (default) */
1545 if (IS_SET(MODE_BLINK))
1548 case 2: /* Steady block */
1549 xdrawglyph(g, cx, cy);
1551 case 3: /* Blinking underline */
1552 if (IS_SET(MODE_BLINK))
1555 case 4: /* Steady underline */
1556 XftDrawRect(xw.draw, &drawcol,
1557 borderpx + cx * win.cw,
1558 borderpx + (cy + 1) * win.ch - \
1560 win.cw, cursorthickness);
1562 case 5: /* Blinking bar */
1563 if (IS_SET(MODE_BLINK))
1566 case 6: /* Steady bar */
1567 XftDrawRect(xw.draw, &drawcol,
1568 borderpx + cx * win.cw,
1569 borderpx + cy * win.ch,
1570 cursorthickness, win.ch);
1572 case 7: /* Blinking st cursor */
1573 if (IS_SET(MODE_BLINK))
1576 case 8: /* Steady st cursor */
1578 xdrawglyph(g, cx, cy);
1582 XftDrawRect(xw.draw, &drawcol,
1583 borderpx + cx * win.cw,
1584 borderpx + cy * win.ch,
1586 XftDrawRect(xw.draw, &drawcol,
1587 borderpx + cx * win.cw,
1588 borderpx + cy * win.ch,
1590 XftDrawRect(xw.draw, &drawcol,
1591 borderpx + (cx + 1) * win.cw - 1,
1592 borderpx + cy * win.ch,
1594 XftDrawRect(xw.draw, &drawcol,
1595 borderpx + cx * win.cw,
1596 borderpx + (cy + 1) * win.ch - 1,
1604 char buf[sizeof(long) * 8 + 1];
1606 snprintf(buf, sizeof(buf), "%lu", xw.win);
1607 setenv("WINDOWID", buf, 1);
1611 xseticontitle(char *p)
1614 DEFAULT(p, opt_title);
1616 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);
1629 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1631 XSetWMName(xw.dpy, xw.win, &prop);
1632 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1639 return IS_SET(MODE_VISIBLE);
1643 xdrawline(Line line, int x1, int y1, int x2)
1645 int i, x, ox, numspecs;
1647 XftGlyphFontSpec *specs = xw.specbuf;
1649 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1651 for (x = x1; x < x2 && i < numspecs; x++) {
1653 if (new.mode == ATTR_WDUMMY)
1655 if (selected(x, y1))
1656 new.mode ^= ATTR_REVERSE;
1657 if (i > 0 && ATTRCMP(base, new)) {
1658 xdrawglyphfontspecs(specs, base, i, ox, y1);
1670 xdrawglyphfontspecs(specs, base, i, ox, y1);
1676 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1678 XSetForeground(xw.dpy, dc.gc,
1679 dc.col[IS_SET(MODE_REVERSE)?
1680 defaultfg : defaultbg].pixel);
1684 xximspot(int x, int y)
1686 if (xw.ime.xic == NULL)
1689 xw.ime.spot.x = borderpx + x * win.cw;
1690 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1692 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1702 visibility(XEvent *ev)
1704 XVisibilityEvent *e = &ev->xvisibility;
1706 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1712 win.mode &= ~MODE_VISIBLE;
1716 xsetpointermotion(int set)
1718 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1719 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1723 xsetmode(int set, unsigned int flags)
1725 int mode = win.mode;
1726 MODBIT(win.mode, set, flags);
1727 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1732 xsetcursor(int cursor)
1734 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1736 win.cursor = cursor;
1737 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1738 win.cursor == 3 || win.cursor == 5 ||
1744 xseturgency(int add)
1746 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1748 MODBIT(h->flags, add, XUrgencyHint);
1749 XSetWMHints(xw.dpy, xw.win, h);
1756 if (!(IS_SET(MODE_FOCUSED)))
1759 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1765 XFocusChangeEvent *e = &ev->xfocus;
1767 if (e->mode == NotifyGrab)
1770 if (ev->type == FocusIn) {
1772 XSetICFocus(xw.ime.xic);
1773 win.mode |= MODE_FOCUSED;
1775 if (IS_SET(MODE_FOCUS))
1776 ttywrite("\033[I", 3, 0);
1779 XUnsetICFocus(xw.ime.xic);
1780 win.mode &= ~MODE_FOCUSED;
1781 if (IS_SET(MODE_FOCUS))
1782 ttywrite("\033[O", 3, 0);
1787 match(uint mask, uint state)
1789 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1793 kmap(KeySym k, uint state)
1798 /* Check for mapped keys out of X11 function keys. */
1799 for (i = 0; i < LEN(mappedkeys); i++) {
1800 if (mappedkeys[i] == k)
1803 if (i == LEN(mappedkeys)) {
1804 if ((k & 0xFFFF) < 0xFD00)
1808 for (kp = key; kp < key + LEN(key); kp++) {
1812 if (!match(kp->mask, state))
1815 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1817 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1820 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1832 XKeyEvent *e = &ev->xkey;
1834 char buf[64], *customkey;
1840 if (IS_SET(MODE_KBDLOCK))
1844 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1846 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1848 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1849 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1850 bp->func(&(bp->arg));
1855 /* 2. custom keys from config.h */
1856 if ((customkey = kmap(ksym, e->state))) {
1857 ttywrite(customkey, strlen(customkey), 1);
1861 /* 3. composed string from input method */
1864 if (len == 1 && e->state & Mod1Mask) {
1865 if (IS_SET(MODE_8BIT)) {
1868 len = utf8encode(c, buf);
1876 ttywrite(buf, len, 1);
1884 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1886 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1887 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1888 win.mode |= MODE_FOCUSED;
1890 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1891 win.mode &= ~MODE_FOCUSED;
1893 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1902 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1905 cresize(e->xconfigure.width, e->xconfigure.height);
1912 int w = win.w, h = win.h;
1914 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1915 struct timespec seltv, *tv, now, lastblink, trigger;
1918 /* Waiting for window mapping */
1920 XNextEvent(xw.dpy, &ev);
1922 * This XFilterEvent call is required because of XOpenIM. It
1923 * does filter out the key event and some client message for
1924 * the input method too.
1926 if (XFilterEvent(&ev, None))
1928 if (ev.type == ConfigureNotify) {
1929 w = ev.xconfigure.width;
1930 h = ev.xconfigure.height;
1932 } while (ev.type != MapNotify);
1934 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1937 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1939 FD_SET(ttyfd, &rfd);
1942 if (XPending(xw.dpy))
1943 timeout = 0; /* existing events might not set xfd */
1945 seltv.tv_sec = timeout / 1E3;
1946 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1947 tv = timeout >= 0 ? &seltv : NULL;
1949 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1952 die("select failed: %s\n", strerror(errno));
1954 clock_gettime(CLOCK_MONOTONIC, &now);
1956 if (FD_ISSET(ttyfd, &rfd))
1960 while (XPending(xw.dpy)) {
1962 XNextEvent(xw.dpy, &ev);
1963 if (XFilterEvent(&ev, None))
1965 if (handler[ev.type])
1966 (handler[ev.type])(&ev);
1970 * To reduce flicker and tearing, when new content or event
1971 * triggers drawing, we first wait a bit to ensure we got
1972 * everything, and if nothing new arrives - we draw.
1973 * We start with trying to wait minlatency ms. If more content
1974 * arrives sooner, we retry with shorter and shorter periods,
1975 * and eventually draw even without idle after maxlatency ms.
1976 * Typically this results in low latency while interacting,
1977 * maximum latency intervals during `cat huge.txt`, and perfect
1978 * sync with periodic updates from animations/key-repeats/etc.
1980 if (FD_ISSET(ttyfd, &rfd) || xev) {
1983 if (IS_SET(MODE_BLINK)) {
1984 win.mode ^= MODE_BLINK;
1989 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1990 / maxlatency * minlatency;
1992 continue; /* we have time, try to find idle */
1995 /* idle detected or maxlatency exhausted -> draw */
1997 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
1998 timeout = blinktimeout - TIMEDIFF(now, lastblink);
2000 if (-timeout > blinktimeout) /* start visible */
2001 win.mode |= MODE_BLINK;
2002 win.mode ^= MODE_BLINK;
2003 tsetdirtattr(ATTR_BLINK);
2005 timeout = blinktimeout;
2018 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2019 " [-n name] [-o file]\n"
2020 " [-T title] [-t title] [-w windowid]"
2021 " [[-e] command [args ...]]\n"
2022 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2023 " [-n name] [-o file]\n"
2024 " [-T title] [-t title] [-w windowid] -l line"
2025 " [stty_args ...]\n", argv0, argv0);
2029 main(int argc, char *argv[])
2033 xsetcursor(cursorstyle);
2040 opt_class = EARGF(usage());
2047 opt_font = EARGF(usage());
2050 xw.gm = XParseGeometry(EARGF(usage()),
2051 &xw.l, &xw.t, &cols, &rows);
2057 opt_io = EARGF(usage());
2060 opt_line = EARGF(usage());
2063 opt_name = EARGF(usage());
2067 opt_title = EARGF(usage());
2070 opt_embed = EARGF(usage());
2073 die("%s " VERSION "\n", argv0);
2080 if (argc > 0) /* eat all remaining arguments */
2084 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2086 setlocale(LC_CTYPE, "");
2087 XSetLocaleModifiers("");
2088 cols = MAX(cols, 1);
2089 rows = MAX(rows, 1);