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>
17 #include <X11/Xresource.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 */
49 /* Xresources preferences */
58 enum resource_type type;
63 #define XK_ANY_MOD UINT_MAX
65 #define XK_SWITCH_MOD (1<<13)
67 /* function definitions used in config.h */
68 static void clipcopy(const Arg *);
69 static void clippaste(const Arg *);
70 static void numlock(const Arg *);
71 static void selpaste(const Arg *);
72 static void zoom(const Arg *);
73 static void zoomabs(const Arg *);
74 static void zoomreset(const Arg *);
75 static void ttysend(const Arg *);
77 /* config.h for applying patches and the configuration. */
81 #define XEMBED_FOCUS_IN 4
82 #define XEMBED_FOCUS_OUT 5
85 #define IS_SET(flag) ((win.mode & (flag)) != 0)
86 #define TRUERED(x) (((x) & 0xff0000) >> 8)
87 #define TRUEGREEN(x) (((x) & 0xff00))
88 #define TRUEBLUE(x) (((x) & 0xff) << 8)
90 typedef XftDraw *Draw;
91 typedef XftColor Color;
92 typedef XftGlyphFontSpec GlyphFontSpec;
94 /* Purely graphic info */
96 int tw, th; /* tty width and height */
97 int w, h; /* window width and height */
98 int ch; /* char height */
99 int cw; /* char width */
100 int mode; /* window state/mode flags */
101 int cursor; /* cursor style */
109 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
110 Atom xembed, wmdeletewin, netwmname, netwmpid;
115 XVaNestedList spotlist;
119 XSetWindowAttributes attrs;
121 int isfixed; /* is fixed geometry? */
122 int l, t; /* left and top offset */
123 int gm; /* geometry mask */
128 char *primary, *clipboard;
129 struct timespec tclick1;
130 struct timespec tclick2;
149 /* Drawing Context */
153 Font font, bfont, ifont, ibfont;
157 static inline ushort sixd_to_16bit(int);
158 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
159 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
160 static void xdrawglyph(Glyph, int, int);
161 static void xclear(int, int, int, int);
162 static int xgeommasktogravity(int);
163 static int ximopen(Display *);
164 static void ximinstantiate(Display *, XPointer, XPointer);
165 static void ximdestroy(XIM, XPointer, XPointer);
166 static int xicdestroy(XIC, XPointer, XPointer);
167 static void xinit(int, int);
168 static void cresize(int, int);
169 static void xresize(int, int);
170 static void xhints(void);
171 static int xloadcolor(int, const char *, Color *);
172 static int xloadfont(Font *, FcPattern *);
173 static void xloadfonts(char *, double);
174 static void xunloadfont(Font *);
175 static void xunloadfonts(void);
176 static void xsetenv(void);
177 static void xseturgency(int);
178 static int evcol(XEvent *);
179 static int evrow(XEvent *);
181 static void expose(XEvent *);
182 static void visibility(XEvent *);
183 static void unmap(XEvent *);
184 static void kpress(XEvent *);
185 static void cmessage(XEvent *);
186 static void resize(XEvent *);
187 static void focus(XEvent *);
188 static uint buttonmask(uint);
189 static int mouseaction(XEvent *, uint);
190 static void brelease(XEvent *);
191 static void bpress(XEvent *);
192 static void bmotion(XEvent *);
193 static void propnotify(XEvent *);
194 static void selnotify(XEvent *);
195 static void selclear_(XEvent *);
196 static void selrequest(XEvent *);
197 static void setsel(char *, Time);
198 static void mousesel(XEvent *, int);
199 static void mousereport(XEvent *);
200 static char *kmap(KeySym, uint);
201 static int match(uint, uint);
203 static void run(void);
204 static void usage(void);
206 static void (*handler[LASTEvent])(XEvent *) = {
208 [ClientMessage] = cmessage,
209 [ConfigureNotify] = resize,
210 [VisibilityNotify] = visibility,
211 [UnmapNotify] = unmap,
215 [MotionNotify] = bmotion,
216 [ButtonPress] = bpress,
217 [ButtonRelease] = brelease,
219 * Uncomment if you want the selection to disappear when you select something
220 * different in another window.
222 /* [SelectionClear] = selclear_, */
223 [SelectionNotify] = selnotify,
225 * PropertyNotify is only turned on when there is some INCR transfer happening
226 * for the selection retrieval.
228 [PropertyNotify] = propnotify,
229 [SelectionRequest] = selrequest,
235 static XSelection xsel;
236 static TermWindow win;
238 /* Font Ring Cache */
252 /* Fontcache is an array now. A new font will be appended to the array. */
253 static Fontcache *frc = NULL;
254 static int frclen = 0;
255 static int frccap = 0;
256 static char *usedfont = NULL;
257 static double usedfontsize = 0;
258 static double defaultfontsize = 0;
260 static char *opt_class = NULL;
261 static char **opt_cmd = NULL;
262 static char *opt_embed = NULL;
263 static char *opt_font = NULL;
264 static char *opt_io = NULL;
265 static char *opt_line = NULL;
266 static char *opt_name = NULL;
267 static char *opt_title = NULL;
269 static int oldbutton = 3; /* button event on startup: 3 = release */
270 static int cursorblinks = 0;
273 clipcopy(const Arg *dummy)
277 free(xsel.clipboard);
278 xsel.clipboard = NULL;
280 if (xsel.primary != NULL) {
281 xsel.clipboard = xstrdup(xsel.primary);
282 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
283 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
288 clippaste(const Arg *dummy)
292 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
293 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
294 xw.win, CurrentTime);
298 selpaste(const Arg *dummy)
300 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
301 xw.win, CurrentTime);
305 numlock(const Arg *dummy)
307 win.mode ^= MODE_NUMLOCK;
315 larg.f = usedfontsize + arg->f;
320 zoomabs(const Arg *arg)
323 xloadfonts(usedfont, arg->f);
330 zoomreset(const Arg *arg)
334 if (defaultfontsize > 0) {
335 larg.f = defaultfontsize;
341 ttysend(const Arg *arg)
343 ttywrite(arg->s, strlen(arg->s), 1);
349 int x = e->xbutton.x - borderpx;
350 LIMIT(x, 0, win.tw - 1);
357 int y = e->xbutton.y - borderpx;
358 LIMIT(y, 0, win.th - 1);
363 mousesel(XEvent *e, int done)
365 int type, seltype = SEL_REGULAR;
366 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
368 for (type = 1; type < LEN(selmasks); ++type) {
369 if (match(selmasks[type], state)) {
374 selextend(evcol(e), evrow(e), seltype, done);
376 setsel(getsel(), e->xbutton.time);
380 mousereport(XEvent *e)
382 int len, x = evcol(e), y = evrow(e),
383 button = e->xbutton.button, state = e->xbutton.state;
388 if (e->xbutton.type == MotionNotify) {
389 if (x == ox && y == oy)
391 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
393 /* MOUSE_MOTION: no reporting if no button is pressed */
394 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
397 button = oldbutton + 32;
401 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
408 if (e->xbutton.type == ButtonPress) {
412 } else if (e->xbutton.type == ButtonRelease) {
414 /* MODE_MOUSEX10: no button release reporting */
415 if (IS_SET(MODE_MOUSEX10))
417 if (button == 64 || button == 65)
422 if (!IS_SET(MODE_MOUSEX10)) {
423 button += ((state & ShiftMask ) ? 4 : 0)
424 + ((state & Mod4Mask ) ? 8 : 0)
425 + ((state & ControlMask) ? 16 : 0);
428 if (IS_SET(MODE_MOUSESGR)) {
429 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
431 e->xbutton.type == ButtonRelease ? 'm' : 'M');
432 } else if (x < 223 && y < 223) {
433 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
434 32+button, 32+x+1, 32+y+1);
439 ttywrite(buf, len, 0);
443 buttonmask(uint button)
445 return button == Button1 ? Button1Mask
446 : button == Button2 ? Button2Mask
447 : button == Button3 ? Button3Mask
448 : button == Button4 ? Button4Mask
449 : button == Button5 ? Button5Mask
454 mouseaction(XEvent *e, uint release)
458 /* ignore Button<N>mask for Button<N> - it's set on release */
459 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
461 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
462 if (ms->release == release &&
463 ms->button == e->xbutton.button &&
464 (match(ms->mod, state) || /* exact or forced */
465 match(ms->mod, state & ~forcemousemod))) {
466 ms->func(&(ms->arg));
480 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
485 if (mouseaction(e, 0))
488 if (e->xbutton.button == Button1) {
490 * If the user clicks below predefined timeouts specific
491 * snapping behaviour is exposed.
493 clock_gettime(CLOCK_MONOTONIC, &now);
494 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
496 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
501 xsel.tclick2 = xsel.tclick1;
504 selstart(evcol(e), evrow(e), snap);
509 propnotify(XEvent *e)
511 XPropertyEvent *xpev;
512 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
514 xpev = &e->xproperty;
515 if (xpev->state == PropertyNewValue &&
516 (xpev->atom == XA_PRIMARY ||
517 xpev->atom == clipboard)) {
525 ulong nitems, ofs, rem;
527 uchar *data, *last, *repl;
528 Atom type, incratom, property = None;
530 incratom = XInternAtom(xw.dpy, "INCR", 0);
533 if (e->type == SelectionNotify)
534 property = e->xselection.property;
535 else if (e->type == PropertyNotify)
536 property = e->xproperty.atom;
538 if (property == None)
542 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
543 BUFSIZ/4, False, AnyPropertyType,
544 &type, &format, &nitems, &rem,
546 fprintf(stderr, "Clipboard allocation failed\n");
550 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
552 * If there is some PropertyNotify with no data, then
553 * this is the signal of the selection owner that all
554 * data has been transferred. We won't need to receive
555 * PropertyNotify events anymore.
557 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
558 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
562 if (type == incratom) {
564 * Activate the PropertyNotify events so we receive
565 * when the selection owner does send us the next
568 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
569 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
573 * Deleting the property is the transfer start signal.
575 XDeleteProperty(xw.dpy, xw.win, (int)property);
581 * Line endings are inconsistent in the terminal and GUI world
582 * copy and pasting. When receiving some selection data,
583 * replace all '\n' with '\r'.
584 * FIXME: Fix the computer world.
587 last = data + nitems * format / 8;
588 while ((repl = memchr(repl, '\n', last - repl))) {
592 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
593 ttywrite("\033[200~", 6, 0);
594 ttywrite((char *)data, nitems * format / 8, 1);
595 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
596 ttywrite("\033[201~", 6, 0);
598 /* number of 32-bit chunks returned */
599 ofs += nitems * format / 32;
603 * Deleting the property again tells the selection owner to send the
604 * next data chunk in the property.
606 XDeleteProperty(xw.dpy, xw.win, (int)property);
622 selrequest(XEvent *e)
624 XSelectionRequestEvent *xsre;
626 Atom xa_targets, string, clipboard;
629 xsre = (XSelectionRequestEvent *) e;
630 xev.type = SelectionNotify;
631 xev.requestor = xsre->requestor;
632 xev.selection = xsre->selection;
633 xev.target = xsre->target;
634 xev.time = xsre->time;
635 if (xsre->property == None)
636 xsre->property = xsre->target;
641 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
642 if (xsre->target == xa_targets) {
643 /* respond with the supported type */
644 string = xsel.xtarget;
645 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
646 XA_ATOM, 32, PropModeReplace,
647 (uchar *) &string, 1);
648 xev.property = xsre->property;
649 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
651 * xith XA_STRING non ascii characters may be incorrect in the
652 * requestor. It is not our problem, use utf8.
654 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
655 if (xsre->selection == XA_PRIMARY) {
656 seltext = xsel.primary;
657 } else if (xsre->selection == clipboard) {
658 seltext = xsel.clipboard;
661 "Unhandled clipboard selection 0x%lx\n",
665 if (seltext != NULL) {
666 XChangeProperty(xsre->display, xsre->requestor,
667 xsre->property, xsre->target,
669 (uchar *)seltext, strlen(seltext));
670 xev.property = xsre->property;
674 /* all done, send a notification to the listener */
675 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
676 fprintf(stderr, "Error sending SelectionNotify event\n");
680 setsel(char *str, Time t)
688 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
689 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
696 setsel(str, CurrentTime);
702 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
707 if (mouseaction(e, 1))
709 if (e->xbutton.button == Button1)
716 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
725 cresize(int width, int height)
734 col = (win.w - 2 * borderpx) / win.cw;
735 row = (win.h - 2 * borderpx) / win.ch;
741 ttyresize(win.tw, win.th);
745 xresize(int col, int row)
747 win.tw = col * win.cw;
748 win.th = row * win.ch;
750 XFreePixmap(xw.dpy, xw.buf);
751 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
752 DefaultDepth(xw.dpy, xw.scr));
753 XftDrawChange(xw.draw, xw.buf);
754 xclear(0, 0, win.w, win.h);
756 /* resize to new width */
757 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
763 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
767 xloadcolor(int i, const char *name, Color *ncolor)
769 XRenderColor color = { .alpha = 0xffff };
772 if (BETWEEN(i, 16, 255)) { /* 256 color */
773 if (i < 6*6*6+16) { /* same colors as xterm */
774 color.red = sixd_to_16bit( ((i-16)/36)%6 );
775 color.green = sixd_to_16bit( ((i-16)/6) %6 );
776 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
777 } else { /* greyscale */
778 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
779 color.green = color.blue = color.red;
781 return XftColorAllocValue(xw.dpy, xw.vis,
782 xw.cmap, &color, ncolor);
787 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
798 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
799 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
801 dc.collen = MAX(LEN(colorname), 256);
802 dc.col = xmalloc(dc.collen * sizeof(Color));
805 for (i = 0; i < dc.collen; i++)
806 if (!xloadcolor(i, NULL, &dc.col[i])) {
808 die("could not allocate color '%s'\n", colorname[i]);
810 die("could not allocate color %d\n", i);
816 xsetcolorname(int x, const char *name)
820 if (!BETWEEN(x, 0, dc.collen))
823 if (!xloadcolor(x, name, &ncolor))
826 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
833 * Absolute coordinates.
836 xclear(int x1, int y1, int x2, int y2)
839 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
840 x1, y1, x2-x1, y2-y1);
846 XClassHint class = {opt_name ? opt_name : "st",
847 opt_class ? opt_class : "St"};
848 XWMHints wm = {.flags = InputHint, .input = 1};
851 sizeh = XAllocSizeHints();
853 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
854 sizeh->height = win.h;
855 sizeh->width = win.w;
856 sizeh->height_inc = win.ch;
857 sizeh->width_inc = win.cw;
858 sizeh->base_height = 2 * borderpx;
859 sizeh->base_width = 2 * borderpx;
860 sizeh->min_height = win.ch + 2 * borderpx;
861 sizeh->min_width = win.cw + 2 * borderpx;
863 sizeh->flags |= PMaxSize;
864 sizeh->min_width = sizeh->max_width = win.w;
865 sizeh->min_height = sizeh->max_height = win.h;
867 if (xw.gm & (XValue|YValue)) {
868 sizeh->flags |= USPosition | PWinGravity;
871 sizeh->win_gravity = xgeommasktogravity(xw.gm);
874 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
880 xgeommasktogravity(int mask)
882 switch (mask & (XNegative|YNegative)) {
884 return NorthWestGravity;
886 return NorthEastGravity;
888 return SouthWestGravity;
891 return SouthEastGravity;
895 xloadfont(Font *f, FcPattern *pattern)
897 FcPattern *configured;
901 int wantattr, haveattr;
904 * Manually configure instead of calling XftMatchFont
905 * so that we can use the configured pattern for
906 * "missing glyph" lookups.
908 configured = FcPatternDuplicate(pattern);
912 FcConfigSubstitute(NULL, configured, FcMatchPattern);
913 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
915 match = FcFontMatch(NULL, configured, &result);
917 FcPatternDestroy(configured);
921 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
922 FcPatternDestroy(configured);
923 FcPatternDestroy(match);
927 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
930 * Check if xft was unable to find a font with the appropriate
931 * slant but gave us one anyway. Try to mitigate.
933 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
934 &haveattr) != XftResultMatch) || haveattr < wantattr) {
936 fputs("font slant does not match\n", stderr);
940 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
942 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
943 &haveattr) != XftResultMatch) || haveattr != wantattr) {
945 fputs("font weight does not match\n", stderr);
949 XftTextExtentsUtf8(xw.dpy, f->match,
950 (const FcChar8 *) ascii_printable,
951 strlen(ascii_printable), &extents);
954 f->pattern = configured;
956 f->ascent = f->match->ascent;
957 f->descent = f->match->descent;
959 f->rbearing = f->match->max_advance_width;
961 f->height = f->ascent + f->descent;
962 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
968 xloadfonts(char *fontstr, double fontsize)
973 if (fontstr[0] == '-')
974 pattern = XftXlfdParse(fontstr, False, False);
976 pattern = FcNameParse((FcChar8 *)fontstr);
979 die("can't open font %s\n", fontstr);
982 FcPatternDel(pattern, FC_PIXEL_SIZE);
983 FcPatternDel(pattern, FC_SIZE);
984 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
985 usedfontsize = fontsize;
987 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
989 usedfontsize = fontval;
990 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
995 * Default font size is 12, if none given. This is to
996 * have a known usedfontsize value.
998 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1001 defaultfontsize = usedfontsize;
1004 if (xloadfont(&dc.font, pattern))
1005 die("can't open font %s\n", fontstr);
1007 if (usedfontsize < 0) {
1008 FcPatternGetDouble(dc.font.match->pattern,
1009 FC_PIXEL_SIZE, 0, &fontval);
1010 usedfontsize = fontval;
1012 defaultfontsize = fontval;
1015 /* Setting character width and height. */
1016 win.cw = ceilf(dc.font.width * cwscale);
1017 win.ch = ceilf(dc.font.height * chscale);
1019 FcPatternDel(pattern, FC_SLANT);
1020 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1021 if (xloadfont(&dc.ifont, pattern))
1022 die("can't open font %s\n", fontstr);
1024 FcPatternDel(pattern, FC_WEIGHT);
1025 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1026 if (xloadfont(&dc.ibfont, pattern))
1027 die("can't open font %s\n", fontstr);
1029 FcPatternDel(pattern, FC_SLANT);
1030 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1031 if (xloadfont(&dc.bfont, pattern))
1032 die("can't open font %s\n", fontstr);
1034 FcPatternDestroy(pattern);
1038 xunloadfont(Font *f)
1040 XftFontClose(xw.dpy, f->match);
1041 FcPatternDestroy(f->pattern);
1043 FcFontSetDestroy(f->set);
1049 /* Free the loaded fonts in the font cache. */
1051 XftFontClose(xw.dpy, frc[--frclen].font);
1053 xunloadfont(&dc.font);
1054 xunloadfont(&dc.bfont);
1055 xunloadfont(&dc.ifont);
1056 xunloadfont(&dc.ibfont);
1060 ximopen(Display *dpy)
1062 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1063 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1065 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1066 if (xw.ime.xim == NULL)
1069 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1070 fprintf(stderr, "XSetIMValues: "
1071 "Could not set XNDestroyCallback.\n");
1073 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1076 if (xw.ime.xic == NULL) {
1077 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1078 XIMPreeditNothing | XIMStatusNothing,
1079 XNClientWindow, xw.win,
1080 XNDestroyCallback, &icdestroy,
1083 if (xw.ime.xic == NULL)
1084 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1090 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1093 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1094 ximinstantiate, NULL);
1098 ximdestroy(XIM xim, XPointer client, XPointer call)
1101 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1102 ximinstantiate, NULL);
1103 XFree(xw.ime.spotlist);
1107 xicdestroy(XIC xim, XPointer client, XPointer call)
1114 xinit(int cols, int rows)
1119 pid_t thispid = getpid();
1120 XColor xmousefg, xmousebg;
1122 xw.scr = XDefaultScreen(xw.dpy);
1123 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1127 die("could not init fontconfig.\n");
1129 usedfont = (opt_font == NULL)? font : opt_font;
1130 xloadfonts(usedfont, 0);
1133 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1136 /* adjust fixed window geometry */
1137 win.w = 2 * borderpx + cols * win.cw;
1138 win.h = 2 * borderpx + rows * win.ch;
1139 if (xw.gm & XNegative)
1140 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1141 if (xw.gm & YNegative)
1142 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1145 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1146 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1147 xw.attrs.bit_gravity = NorthWestGravity;
1148 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1149 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1150 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1151 xw.attrs.colormap = xw.cmap;
1153 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1154 parent = XRootWindow(xw.dpy, xw.scr);
1155 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1156 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1157 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1158 | CWEventMask | CWColormap, &xw.attrs);
1160 memset(&gcvalues, 0, sizeof(gcvalues));
1161 gcvalues.graphics_exposures = False;
1162 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1164 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1165 DefaultDepth(xw.dpy, xw.scr));
1166 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1167 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1169 /* font spec buffer */
1170 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1172 /* Xft rendering context */
1173 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1176 if (!ximopen(xw.dpy)) {
1177 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1178 ximinstantiate, NULL);
1181 /* white cursor, black outline */
1182 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1183 XDefineCursor(xw.dpy, xw.win, cursor);
1185 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1186 xmousefg.red = 0xffff;
1187 xmousefg.green = 0xffff;
1188 xmousefg.blue = 0xffff;
1191 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1192 xmousebg.red = 0x0000;
1193 xmousebg.green = 0x0000;
1194 xmousebg.blue = 0x0000;
1197 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1199 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1200 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1201 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1202 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1204 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1205 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1206 PropModeReplace, (uchar *)&thispid, 1);
1208 win.mode = MODE_NUMLOCK;
1211 XMapWindow(xw.dpy, xw.win);
1212 XSync(xw.dpy, False);
1214 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1215 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1216 xsel.primary = NULL;
1217 xsel.clipboard = NULL;
1218 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1219 if (xsel.xtarget == None)
1220 xsel.xtarget = XA_STRING;
1224 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1226 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1227 ushort mode, prevmode = USHRT_MAX;
1228 Font *font = &dc.font;
1229 int frcflags = FRC_NORMAL;
1230 float runewidth = win.cw;
1234 FcPattern *fcpattern, *fontpattern;
1235 FcFontSet *fcsets[] = { NULL };
1236 FcCharSet *fccharset;
1237 int i, f, numspecs = 0;
1239 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1240 /* Fetch rune and mode for current glyph. */
1242 mode = glyphs[i].mode;
1244 /* Skip dummy wide-character spacing. */
1245 if (mode == ATTR_WDUMMY)
1248 /* Determine font for glyph if different from previous glyph. */
1249 if (prevmode != mode) {
1252 frcflags = FRC_NORMAL;
1253 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1254 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1256 frcflags = FRC_ITALICBOLD;
1257 } else if (mode & ATTR_ITALIC) {
1259 frcflags = FRC_ITALIC;
1260 } else if (mode & ATTR_BOLD) {
1262 frcflags = FRC_BOLD;
1264 yp = winy + font->ascent;
1267 /* Lookup character index with default font. */
1268 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1270 specs[numspecs].font = font->match;
1271 specs[numspecs].glyph = glyphidx;
1272 specs[numspecs].x = (short)xp;
1273 specs[numspecs].y = (short)yp;
1279 /* Fallback on font cache, search the font cache for match. */
1280 for (f = 0; f < frclen; f++) {
1281 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1282 /* Everything correct. */
1283 if (glyphidx && frc[f].flags == frcflags)
1285 /* We got a default font for a not found glyph. */
1286 if (!glyphidx && frc[f].flags == frcflags
1287 && frc[f].unicodep == rune) {
1292 /* Nothing was found. Use fontconfig to find matching font. */
1295 font->set = FcFontSort(0, font->pattern,
1297 fcsets[0] = font->set;
1300 * Nothing was found in the cache. Now use
1301 * some dozen of Fontconfig calls to get the
1302 * font for one single character.
1304 * Xft and fontconfig are design failures.
1306 fcpattern = FcPatternDuplicate(font->pattern);
1307 fccharset = FcCharSetCreate();
1309 FcCharSetAddChar(fccharset, rune);
1310 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1312 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1314 FcConfigSubstitute(0, fcpattern,
1316 FcDefaultSubstitute(fcpattern);
1318 fontpattern = FcFontSetMatch(0, fcsets, 1,
1321 /* Allocate memory for the new cache entry. */
1322 if (frclen >= frccap) {
1324 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1327 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1329 if (!frc[frclen].font)
1330 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1332 frc[frclen].flags = frcflags;
1333 frc[frclen].unicodep = rune;
1335 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1340 FcPatternDestroy(fcpattern);
1341 FcCharSetDestroy(fccharset);
1344 specs[numspecs].font = frc[f].font;
1345 specs[numspecs].glyph = glyphidx;
1346 specs[numspecs].x = (short)xp;
1347 specs[numspecs].y = (short)yp;
1356 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1358 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1359 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1360 width = charlen * win.cw;
1361 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1362 XRenderColor colfg, colbg;
1365 /* Fallback on color display for attributes not supported by the font */
1366 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1367 if (dc.ibfont.badslant || dc.ibfont.badweight)
1368 base.fg = defaultattr;
1369 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1370 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
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 + 1,
1481 if (base.mode & ATTR_STRUCK) {
1482 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 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 */
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);
1613 DEFAULT(p, opt_title);
1615 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1617 XSetWMName(xw.dpy, xw.win, &prop);
1618 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1625 return IS_SET(MODE_VISIBLE);
1629 xdrawline(Line line, int x1, int y1, int x2)
1631 int i, x, ox, numspecs;
1633 XftGlyphFontSpec *specs = xw.specbuf;
1635 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1637 for (x = x1; x < x2 && i < numspecs; x++) {
1639 if (new.mode == ATTR_WDUMMY)
1641 if (selected(x, y1))
1642 new.mode ^= ATTR_REVERSE;
1643 if (i > 0 && ATTRCMP(base, new)) {
1644 xdrawglyphfontspecs(specs, base, i, ox, y1);
1656 xdrawglyphfontspecs(specs, base, i, ox, y1);
1662 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1664 XSetForeground(xw.dpy, dc.gc,
1665 dc.col[IS_SET(MODE_REVERSE)?
1666 defaultfg : defaultbg].pixel);
1670 xximspot(int x, int y)
1672 if (xw.ime.xic == NULL)
1675 xw.ime.spot.x = borderpx + x * win.cw;
1676 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1678 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1688 visibility(XEvent *ev)
1690 XVisibilityEvent *e = &ev->xvisibility;
1692 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1698 win.mode &= ~MODE_VISIBLE;
1702 xsetpointermotion(int set)
1704 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1705 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1709 xsetmode(int set, unsigned int flags)
1711 int mode = win.mode;
1712 MODBIT(win.mode, set, flags);
1713 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1718 xsetcursor(int cursor)
1720 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1722 win.cursor = cursor;
1723 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1724 win.cursor == 3 || win.cursor == 5 ||
1730 xseturgency(int add)
1732 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1734 MODBIT(h->flags, add, XUrgencyHint);
1735 XSetWMHints(xw.dpy, xw.win, h);
1742 if (!(IS_SET(MODE_FOCUSED)))
1745 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1751 XFocusChangeEvent *e = &ev->xfocus;
1753 if (e->mode == NotifyGrab)
1756 if (ev->type == FocusIn) {
1758 XSetICFocus(xw.ime.xic);
1759 win.mode |= MODE_FOCUSED;
1761 if (IS_SET(MODE_FOCUS))
1762 ttywrite("\033[I", 3, 0);
1765 XUnsetICFocus(xw.ime.xic);
1766 win.mode &= ~MODE_FOCUSED;
1767 if (IS_SET(MODE_FOCUS))
1768 ttywrite("\033[O", 3, 0);
1773 match(uint mask, uint state)
1775 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1779 kmap(KeySym k, uint state)
1784 /* Check for mapped keys out of X11 function keys. */
1785 for (i = 0; i < LEN(mappedkeys); i++) {
1786 if (mappedkeys[i] == k)
1789 if (i == LEN(mappedkeys)) {
1790 if ((k & 0xFFFF) < 0xFD00)
1794 for (kp = key; kp < key + LEN(key); kp++) {
1798 if (!match(kp->mask, state))
1801 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1803 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1806 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1818 XKeyEvent *e = &ev->xkey;
1820 char buf[64], *customkey;
1826 if (IS_SET(MODE_KBDLOCK))
1830 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1832 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1834 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1835 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1836 bp->func(&(bp->arg));
1841 /* 2. custom keys from config.h */
1842 if ((customkey = kmap(ksym, e->state))) {
1843 ttywrite(customkey, strlen(customkey), 1);
1847 /* 3. composed string from input method */
1850 if (len == 1 && e->state & Mod1Mask) {
1851 if (IS_SET(MODE_8BIT)) {
1854 len = utf8encode(c, buf);
1862 ttywrite(buf, len, 1);
1870 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1872 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1873 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1874 win.mode |= MODE_FOCUSED;
1876 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1877 win.mode &= ~MODE_FOCUSED;
1879 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1888 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1891 cresize(e->xconfigure.width, e->xconfigure.height);
1898 int w = win.w, h = win.h;
1900 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1901 struct timespec seltv, *tv, now, lastblink, trigger;
1904 /* Waiting for window mapping */
1906 XNextEvent(xw.dpy, &ev);
1908 * This XFilterEvent call is required because of XOpenIM. It
1909 * does filter out the key event and some client message for
1910 * the input method too.
1912 if (XFilterEvent(&ev, None))
1914 if (ev.type == ConfigureNotify) {
1915 w = ev.xconfigure.width;
1916 h = ev.xconfigure.height;
1918 } while (ev.type != MapNotify);
1920 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1923 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1925 FD_SET(ttyfd, &rfd);
1928 if (XPending(xw.dpy))
1929 timeout = 0; /* existing events might not set xfd */
1931 seltv.tv_sec = timeout / 1E3;
1932 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1933 tv = timeout >= 0 ? &seltv : NULL;
1935 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1938 die("select failed: %s\n", strerror(errno));
1940 clock_gettime(CLOCK_MONOTONIC, &now);
1942 if (FD_ISSET(ttyfd, &rfd))
1946 while (XPending(xw.dpy)) {
1948 XNextEvent(xw.dpy, &ev);
1949 if (XFilterEvent(&ev, None))
1951 if (handler[ev.type])
1952 (handler[ev.type])(&ev);
1956 * To reduce flicker and tearing, when new content or event
1957 * triggers drawing, we first wait a bit to ensure we got
1958 * everything, and if nothing new arrives - we draw.
1959 * We start with trying to wait minlatency ms. If more content
1960 * arrives sooner, we retry with shorter and shorter periods,
1961 * and eventually draw even without idle after maxlatency ms.
1962 * Typically this results in low latency while interacting,
1963 * maximum latency intervals during `cat huge.txt`, and perfect
1964 * sync with periodic updates from animations/key-repeats/etc.
1966 if (FD_ISSET(ttyfd, &rfd) || xev) {
1969 if (IS_SET(MODE_BLINK)) {
1970 win.mode ^= MODE_BLINK;
1975 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1976 / maxlatency * minlatency;
1978 continue; /* we have time, try to find idle */
1981 /* idle detected or maxlatency exhausted -> draw */
1983 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
1984 timeout = blinktimeout - TIMEDIFF(now, lastblink);
1986 if (-timeout > blinktimeout) /* start visible */
1987 win.mode |= MODE_BLINK;
1988 win.mode ^= MODE_BLINK;
1989 tsetdirtattr(ATTR_BLINK);
1991 timeout = blinktimeout;
2002 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2009 char fullclass[256];
2013 snprintf(fullname, sizeof(fullname), "%s.%s",
2014 opt_name ? opt_name : "st", name);
2015 snprintf(fullclass, sizeof(fullclass), "%s.%s",
2016 opt_class ? opt_class : "St", name);
2017 fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
2019 XrmGetResource(db, fullname, fullclass, &type, &ret);
2020 if (ret.addr == NULL || strncmp("String", type, 64))
2028 *idst = strtoul(ret.addr, NULL, 10);
2031 *fdst = strtof(ret.addr, NULL);
2045 resm = XResourceManagerString(xw.dpy);
2049 db = XrmGetStringDatabase(resm);
2050 for (p = resources; p < resources + LEN(resources); p++)
2051 resource_load(db, p->name, p->type, p->dst);
2057 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2058 " [-n name] [-o file]\n"
2059 " [-T title] [-t title] [-w windowid]"
2060 " [[-e] command [args ...]]\n"
2061 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2062 " [-n name] [-o file]\n"
2063 " [-T title] [-t title] [-w windowid] -l line"
2064 " [stty_args ...]\n", argv0, argv0);
2068 main(int argc, char *argv[])
2072 xsetcursor(cursorstyle);
2079 opt_class = EARGF(usage());
2086 opt_font = EARGF(usage());
2089 xw.gm = XParseGeometry(EARGF(usage()),
2090 &xw.l, &xw.t, &cols, &rows);
2096 opt_io = EARGF(usage());
2099 opt_line = EARGF(usage());
2102 opt_name = EARGF(usage());
2106 opt_title = EARGF(usage());
2109 opt_embed = EARGF(usage());
2112 die("%s " VERSION "\n", argv0);
2119 if (argc > 0) /* eat all remaining arguments */
2123 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2125 setlocale(LC_CTYPE, "");
2126 XSetLocaleModifiers("");
2128 if(!(xw.dpy = XOpenDisplay(NULL)))
2129 die("Can't open display\n");
2132 cols = MAX(cols, 1);
2133 rows = MAX(rows, 1);