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 */
272 clipcopy(const Arg *dummy)
276 free(xsel.clipboard);
277 xsel.clipboard = NULL;
279 if (xsel.primary != NULL) {
280 xsel.clipboard = xstrdup(xsel.primary);
281 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
282 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
287 clippaste(const Arg *dummy)
291 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
292 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
293 xw.win, CurrentTime);
297 selpaste(const Arg *dummy)
299 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
300 xw.win, CurrentTime);
304 numlock(const Arg *dummy)
306 win.mode ^= MODE_NUMLOCK;
314 larg.f = usedfontsize + arg->f;
319 zoomabs(const Arg *arg)
322 xloadfonts(usedfont, arg->f);
329 zoomreset(const Arg *arg)
333 if (defaultfontsize > 0) {
334 larg.f = defaultfontsize;
340 ttysend(const Arg *arg)
342 ttywrite(arg->s, strlen(arg->s), 1);
348 int x = e->xbutton.x - borderpx;
349 LIMIT(x, 0, win.tw - 1);
356 int y = e->xbutton.y - borderpx;
357 LIMIT(y, 0, win.th - 1);
362 mousesel(XEvent *e, int done)
364 int type, seltype = SEL_REGULAR;
365 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
367 for (type = 1; type < LEN(selmasks); ++type) {
368 if (match(selmasks[type], state)) {
373 selextend(evcol(e), evrow(e), seltype, done);
375 setsel(getsel(), e->xbutton.time);
379 mousereport(XEvent *e)
381 int len, x = evcol(e), y = evrow(e),
382 button = e->xbutton.button, state = e->xbutton.state;
387 if (e->xbutton.type == MotionNotify) {
388 if (x == ox && y == oy)
390 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
392 /* MOUSE_MOTION: no reporting if no button is pressed */
393 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
396 button = oldbutton + 32;
400 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
407 if (e->xbutton.type == ButtonPress) {
411 } else if (e->xbutton.type == ButtonRelease) {
413 /* MODE_MOUSEX10: no button release reporting */
414 if (IS_SET(MODE_MOUSEX10))
416 if (button == 64 || button == 65)
421 if (!IS_SET(MODE_MOUSEX10)) {
422 button += ((state & ShiftMask ) ? 4 : 0)
423 + ((state & Mod4Mask ) ? 8 : 0)
424 + ((state & ControlMask) ? 16 : 0);
427 if (IS_SET(MODE_MOUSESGR)) {
428 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
430 e->xbutton.type == ButtonRelease ? 'm' : 'M');
431 } else if (x < 223 && y < 223) {
432 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
433 32+button, 32+x+1, 32+y+1);
438 ttywrite(buf, len, 0);
442 buttonmask(uint button)
444 return button == Button1 ? Button1Mask
445 : button == Button2 ? Button2Mask
446 : button == Button3 ? Button3Mask
447 : button == Button4 ? Button4Mask
448 : button == Button5 ? Button5Mask
453 mouseaction(XEvent *e, uint release)
457 /* ignore Button<N>mask for Button<N> - it's set on release */
458 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
460 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
461 if (ms->release == release &&
462 ms->button == e->xbutton.button &&
463 (match(ms->mod, state) || /* exact or forced */
464 match(ms->mod, state & ~forcemousemod))) {
465 ms->func(&(ms->arg));
479 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
484 if (mouseaction(e, 0))
487 if (e->xbutton.button == 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 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
706 if (mouseaction(e, 1))
708 if (e->xbutton.button == Button1)
715 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
724 cresize(int width, int height)
733 col = (win.w - 2 * borderpx) / win.cw;
734 row = (win.h - 2 * borderpx) / win.ch;
740 ttyresize(win.tw, win.th);
744 xresize(int col, int row)
746 win.tw = col * win.cw;
747 win.th = row * win.ch;
749 XFreePixmap(xw.dpy, xw.buf);
750 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
751 DefaultDepth(xw.dpy, xw.scr));
752 XftDrawChange(xw.draw, xw.buf);
753 xclear(0, 0, win.w, win.h);
755 /* resize to new width */
756 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
762 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
766 xloadcolor(int i, const char *name, Color *ncolor)
768 XRenderColor color = { .alpha = 0xffff };
771 if (BETWEEN(i, 16, 255)) { /* 256 color */
772 if (i < 6*6*6+16) { /* same colors as xterm */
773 color.red = sixd_to_16bit( ((i-16)/36)%6 );
774 color.green = sixd_to_16bit( ((i-16)/6) %6 );
775 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
776 } else { /* greyscale */
777 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
778 color.green = color.blue = color.red;
780 return XftColorAllocValue(xw.dpy, xw.vis,
781 xw.cmap, &color, ncolor);
786 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
797 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
798 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
800 dc.collen = MAX(LEN(colorname), 256);
801 dc.col = xmalloc(dc.collen * sizeof(Color));
804 for (i = 0; i < dc.collen; i++)
805 if (!xloadcolor(i, NULL, &dc.col[i])) {
807 die("could not allocate color '%s'\n", colorname[i]);
809 die("could not allocate color %d\n", i);
815 xsetcolorname(int x, const char *name)
819 if (!BETWEEN(x, 0, dc.collen))
822 if (!xloadcolor(x, name, &ncolor))
825 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
832 * Absolute coordinates.
835 xclear(int x1, int y1, int x2, int y2)
838 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
839 x1, y1, x2-x1, y2-y1);
845 XClassHint class = {opt_name ? opt_name : "st",
846 opt_class ? opt_class : "St"};
847 XWMHints wm = {.flags = InputHint, .input = 1};
850 sizeh = XAllocSizeHints();
852 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
853 sizeh->height = win.h;
854 sizeh->width = win.w;
855 sizeh->height_inc = win.ch;
856 sizeh->width_inc = win.cw;
857 sizeh->base_height = 2 * borderpx;
858 sizeh->base_width = 2 * borderpx;
859 sizeh->min_height = win.ch + 2 * borderpx;
860 sizeh->min_width = win.cw + 2 * borderpx;
862 sizeh->flags |= PMaxSize;
863 sizeh->min_width = sizeh->max_width = win.w;
864 sizeh->min_height = sizeh->max_height = win.h;
866 if (xw.gm & (XValue|YValue)) {
867 sizeh->flags |= USPosition | PWinGravity;
870 sizeh->win_gravity = xgeommasktogravity(xw.gm);
873 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
879 xgeommasktogravity(int mask)
881 switch (mask & (XNegative|YNegative)) {
883 return NorthWestGravity;
885 return NorthEastGravity;
887 return SouthWestGravity;
890 return SouthEastGravity;
894 xloadfont(Font *f, FcPattern *pattern)
896 FcPattern *configured;
900 int wantattr, haveattr;
903 * Manually configure instead of calling XftMatchFont
904 * so that we can use the configured pattern for
905 * "missing glyph" lookups.
907 configured = FcPatternDuplicate(pattern);
911 FcConfigSubstitute(NULL, configured, FcMatchPattern);
912 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
914 match = FcFontMatch(NULL, configured, &result);
916 FcPatternDestroy(configured);
920 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
921 FcPatternDestroy(configured);
922 FcPatternDestroy(match);
926 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
929 * Check if xft was unable to find a font with the appropriate
930 * slant but gave us one anyway. Try to mitigate.
932 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
933 &haveattr) != XftResultMatch) || haveattr < wantattr) {
935 fputs("font slant does not match\n", stderr);
939 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
941 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
942 &haveattr) != XftResultMatch) || haveattr != wantattr) {
944 fputs("font weight does not match\n", stderr);
948 XftTextExtentsUtf8(xw.dpy, f->match,
949 (const FcChar8 *) ascii_printable,
950 strlen(ascii_printable), &extents);
953 f->pattern = configured;
955 f->ascent = f->match->ascent;
956 f->descent = f->match->descent;
958 f->rbearing = f->match->max_advance_width;
960 f->height = f->ascent + f->descent;
961 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
967 xloadfonts(char *fontstr, double fontsize)
972 if (fontstr[0] == '-')
973 pattern = XftXlfdParse(fontstr, False, False);
975 pattern = FcNameParse((FcChar8 *)fontstr);
978 die("can't open font %s\n", fontstr);
981 FcPatternDel(pattern, FC_PIXEL_SIZE);
982 FcPatternDel(pattern, FC_SIZE);
983 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
984 usedfontsize = fontsize;
986 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
988 usedfontsize = fontval;
989 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
994 * Default font size is 12, if none given. This is to
995 * have a known usedfontsize value.
997 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1000 defaultfontsize = usedfontsize;
1003 if (xloadfont(&dc.font, pattern))
1004 die("can't open font %s\n", fontstr);
1006 if (usedfontsize < 0) {
1007 FcPatternGetDouble(dc.font.match->pattern,
1008 FC_PIXEL_SIZE, 0, &fontval);
1009 usedfontsize = fontval;
1011 defaultfontsize = fontval;
1014 /* Setting character width and height. */
1015 win.cw = ceilf(dc.font.width * cwscale);
1016 win.ch = ceilf(dc.font.height * chscale);
1018 FcPatternDel(pattern, FC_SLANT);
1019 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1020 if (xloadfont(&dc.ifont, pattern))
1021 die("can't open font %s\n", fontstr);
1023 FcPatternDel(pattern, FC_WEIGHT);
1024 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1025 if (xloadfont(&dc.ibfont, pattern))
1026 die("can't open font %s\n", fontstr);
1028 FcPatternDel(pattern, FC_SLANT);
1029 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1030 if (xloadfont(&dc.bfont, pattern))
1031 die("can't open font %s\n", fontstr);
1033 FcPatternDestroy(pattern);
1037 xunloadfont(Font *f)
1039 XftFontClose(xw.dpy, f->match);
1040 FcPatternDestroy(f->pattern);
1042 FcFontSetDestroy(f->set);
1048 /* Free the loaded fonts in the font cache. */
1050 XftFontClose(xw.dpy, frc[--frclen].font);
1052 xunloadfont(&dc.font);
1053 xunloadfont(&dc.bfont);
1054 xunloadfont(&dc.ifont);
1055 xunloadfont(&dc.ibfont);
1059 ximopen(Display *dpy)
1061 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1062 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1064 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1065 if (xw.ime.xim == NULL)
1068 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1069 fprintf(stderr, "XSetIMValues: "
1070 "Could not set XNDestroyCallback.\n");
1072 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1075 if (xw.ime.xic == NULL) {
1076 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1077 XIMPreeditNothing | XIMStatusNothing,
1078 XNClientWindow, xw.win,
1079 XNDestroyCallback, &icdestroy,
1082 if (xw.ime.xic == NULL)
1083 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1089 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1092 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1093 ximinstantiate, NULL);
1097 ximdestroy(XIM xim, XPointer client, XPointer call)
1100 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1101 ximinstantiate, NULL);
1102 XFree(xw.ime.spotlist);
1106 xicdestroy(XIC xim, XPointer client, XPointer call)
1113 xinit(int cols, int rows)
1118 pid_t thispid = getpid();
1119 XColor xmousefg, xmousebg;
1121 xw.scr = XDefaultScreen(xw.dpy);
1122 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1126 die("could not init fontconfig.\n");
1128 usedfont = (opt_font == NULL)? font : opt_font;
1129 xloadfonts(usedfont, 0);
1132 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1135 /* adjust fixed window geometry */
1136 win.w = 2 * borderpx + cols * win.cw;
1137 win.h = 2 * borderpx + rows * win.ch;
1138 if (xw.gm & XNegative)
1139 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1140 if (xw.gm & YNegative)
1141 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1144 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1145 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1146 xw.attrs.bit_gravity = NorthWestGravity;
1147 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1148 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1149 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1150 xw.attrs.colormap = xw.cmap;
1152 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1153 parent = XRootWindow(xw.dpy, xw.scr);
1154 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1155 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1156 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1157 | CWEventMask | CWColormap, &xw.attrs);
1159 memset(&gcvalues, 0, sizeof(gcvalues));
1160 gcvalues.graphics_exposures = False;
1161 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1163 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1164 DefaultDepth(xw.dpy, xw.scr));
1165 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1166 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1168 /* font spec buffer */
1169 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1171 /* Xft rendering context */
1172 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1175 if (!ximopen(xw.dpy)) {
1176 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1177 ximinstantiate, NULL);
1180 /* white cursor, black outline */
1181 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1182 XDefineCursor(xw.dpy, xw.win, cursor);
1184 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1185 xmousefg.red = 0xffff;
1186 xmousefg.green = 0xffff;
1187 xmousefg.blue = 0xffff;
1190 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1191 xmousebg.red = 0x0000;
1192 xmousebg.green = 0x0000;
1193 xmousebg.blue = 0x0000;
1196 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1198 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1199 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1200 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1201 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1203 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1204 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1205 PropModeReplace, (uchar *)&thispid, 1);
1207 win.mode = MODE_NUMLOCK;
1210 XMapWindow(xw.dpy, xw.win);
1211 XSync(xw.dpy, False);
1213 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1214 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1215 xsel.primary = NULL;
1216 xsel.clipboard = NULL;
1217 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1218 if (xsel.xtarget == None)
1219 xsel.xtarget = XA_STRING;
1223 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1225 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1226 ushort mode, prevmode = USHRT_MAX;
1227 Font *font = &dc.font;
1228 int frcflags = FRC_NORMAL;
1229 float runewidth = win.cw;
1233 FcPattern *fcpattern, *fontpattern;
1234 FcFontSet *fcsets[] = { NULL };
1235 FcCharSet *fccharset;
1236 int i, f, numspecs = 0;
1238 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1239 /* Fetch rune and mode for current glyph. */
1241 mode = glyphs[i].mode;
1243 /* Skip dummy wide-character spacing. */
1244 if (mode == ATTR_WDUMMY)
1247 /* Determine font for glyph if different from previous glyph. */
1248 if (prevmode != mode) {
1251 frcflags = FRC_NORMAL;
1252 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1253 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1255 frcflags = FRC_ITALICBOLD;
1256 } else if (mode & ATTR_ITALIC) {
1258 frcflags = FRC_ITALIC;
1259 } else if (mode & ATTR_BOLD) {
1261 frcflags = FRC_BOLD;
1263 yp = winy + font->ascent;
1266 /* Lookup character index with default font. */
1267 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1269 specs[numspecs].font = font->match;
1270 specs[numspecs].glyph = glyphidx;
1271 specs[numspecs].x = (short)xp;
1272 specs[numspecs].y = (short)yp;
1278 /* Fallback on font cache, search the font cache for match. */
1279 for (f = 0; f < frclen; f++) {
1280 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1281 /* Everything correct. */
1282 if (glyphidx && frc[f].flags == frcflags)
1284 /* We got a default font for a not found glyph. */
1285 if (!glyphidx && frc[f].flags == frcflags
1286 && frc[f].unicodep == rune) {
1291 /* Nothing was found. Use fontconfig to find matching font. */
1294 font->set = FcFontSort(0, font->pattern,
1296 fcsets[0] = font->set;
1299 * Nothing was found in the cache. Now use
1300 * some dozen of Fontconfig calls to get the
1301 * font for one single character.
1303 * Xft and fontconfig are design failures.
1305 fcpattern = FcPatternDuplicate(font->pattern);
1306 fccharset = FcCharSetCreate();
1308 FcCharSetAddChar(fccharset, rune);
1309 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1311 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1313 FcConfigSubstitute(0, fcpattern,
1315 FcDefaultSubstitute(fcpattern);
1317 fontpattern = FcFontSetMatch(0, fcsets, 1,
1320 /* Allocate memory for the new cache entry. */
1321 if (frclen >= frccap) {
1323 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1326 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1328 if (!frc[frclen].font)
1329 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1331 frc[frclen].flags = frcflags;
1332 frc[frclen].unicodep = rune;
1334 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1339 FcPatternDestroy(fcpattern);
1340 FcCharSetDestroy(fccharset);
1343 specs[numspecs].font = frc[f].font;
1344 specs[numspecs].glyph = glyphidx;
1345 specs[numspecs].x = (short)xp;
1346 specs[numspecs].y = (short)yp;
1355 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1357 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1358 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1359 width = charlen * win.cw;
1360 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1361 XRenderColor colfg, colbg;
1364 /* Fallback on color display for attributes not supported by the font */
1365 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1366 if (dc.ibfont.badslant || dc.ibfont.badweight)
1367 base.fg = defaultattr;
1368 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1369 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1370 base.fg = defaultattr;
1373 if (IS_TRUECOL(base.fg)) {
1374 colfg.alpha = 0xffff;
1375 colfg.red = TRUERED(base.fg);
1376 colfg.green = TRUEGREEN(base.fg);
1377 colfg.blue = TRUEBLUE(base.fg);
1378 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1381 fg = &dc.col[base.fg];
1384 if (IS_TRUECOL(base.bg)) {
1385 colbg.alpha = 0xffff;
1386 colbg.green = TRUEGREEN(base.bg);
1387 colbg.red = TRUERED(base.bg);
1388 colbg.blue = TRUEBLUE(base.bg);
1389 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1392 bg = &dc.col[base.bg];
1395 /* Change basic system colors [0-7] to bright system colors [8-15] */
1396 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1397 fg = &dc.col[base.fg + 8];
1399 if (IS_SET(MODE_REVERSE)) {
1400 if (fg == &dc.col[defaultfg]) {
1401 fg = &dc.col[defaultbg];
1403 colfg.red = ~fg->color.red;
1404 colfg.green = ~fg->color.green;
1405 colfg.blue = ~fg->color.blue;
1406 colfg.alpha = fg->color.alpha;
1407 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1412 if (bg == &dc.col[defaultbg]) {
1413 bg = &dc.col[defaultfg];
1415 colbg.red = ~bg->color.red;
1416 colbg.green = ~bg->color.green;
1417 colbg.blue = ~bg->color.blue;
1418 colbg.alpha = bg->color.alpha;
1419 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1425 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1426 colfg.red = fg->color.red / 2;
1427 colfg.green = fg->color.green / 2;
1428 colfg.blue = fg->color.blue / 2;
1429 colfg.alpha = fg->color.alpha;
1430 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1434 if (base.mode & ATTR_REVERSE) {
1440 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1443 if (base.mode & ATTR_INVISIBLE)
1446 /* Intelligent cleaning up of the borders. */
1448 xclear(0, (y == 0)? 0 : winy, borderpx,
1450 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1452 if (winx + width >= borderpx + win.tw) {
1453 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1454 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1457 xclear(winx, 0, winx + width, borderpx);
1458 if (winy + win.ch >= borderpx + win.th)
1459 xclear(winx, winy + win.ch, winx + width, win.h);
1461 /* Clean up the region we want to draw to. */
1462 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1464 /* Set the clip region because Xft is sometimes dirty. */
1469 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1471 /* Render the glyphs. */
1472 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1474 /* Render underline and strikethrough. */
1475 if (base.mode & ATTR_UNDERLINE) {
1476 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1480 if (base.mode & ATTR_STRUCK) {
1481 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1485 /* Reset clip to none. */
1486 XftDrawSetClip(xw.draw, 0);
1490 xdrawglyph(Glyph g, int x, int y)
1493 XftGlyphFontSpec spec;
1495 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1496 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1500 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1504 /* remove the old cursor */
1505 if (selected(ox, oy))
1506 og.mode ^= ATTR_REVERSE;
1507 xdrawglyph(og, ox, oy);
1509 if (IS_SET(MODE_HIDE))
1513 * Select the right color for the right mode.
1515 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1517 if (IS_SET(MODE_REVERSE)) {
1518 g.mode |= ATTR_REVERSE;
1520 if (selected(cx, cy)) {
1521 drawcol = dc.col[defaultcs];
1524 drawcol = dc.col[defaultrcs];
1528 if (selected(cx, cy)) {
1535 drawcol = dc.col[g.bg];
1538 /* draw the new one */
1539 if (IS_SET(MODE_FOCUSED)) {
1540 switch (win.cursor) {
1541 case 7: /* st extension */
1542 g.u = 0x2603; /* snowman (U+2603) */
1544 case 0: /* Blinking Block */
1545 case 1: /* Blinking Block (Default) */
1546 case 2: /* Steady Block */
1547 xdrawglyph(g, cx, cy);
1549 case 3: /* Blinking Underline */
1550 case 4: /* Steady Underline */
1551 XftDrawRect(xw.draw, &drawcol,
1552 borderpx + cx * win.cw,
1553 borderpx + (cy + 1) * win.ch - \
1555 win.cw, cursorthickness);
1557 case 5: /* Blinking bar */
1558 case 6: /* Steady bar */
1559 XftDrawRect(xw.draw, &drawcol,
1560 borderpx + cx * win.cw,
1561 borderpx + cy * win.ch,
1562 cursorthickness, win.ch);
1566 XftDrawRect(xw.draw, &drawcol,
1567 borderpx + cx * win.cw,
1568 borderpx + cy * win.ch,
1570 XftDrawRect(xw.draw, &drawcol,
1571 borderpx + cx * win.cw,
1572 borderpx + cy * win.ch,
1574 XftDrawRect(xw.draw, &drawcol,
1575 borderpx + (cx + 1) * win.cw - 1,
1576 borderpx + cy * win.ch,
1578 XftDrawRect(xw.draw, &drawcol,
1579 borderpx + cx * win.cw,
1580 borderpx + (cy + 1) * win.ch - 1,
1588 char buf[sizeof(long) * 8 + 1];
1590 snprintf(buf, sizeof(buf), "%lu", xw.win);
1591 setenv("WINDOWID", buf, 1);
1598 DEFAULT(p, opt_title);
1600 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1602 XSetWMName(xw.dpy, xw.win, &prop);
1603 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1610 return IS_SET(MODE_VISIBLE);
1614 xdrawline(Line line, int x1, int y1, int x2)
1616 int i, x, ox, numspecs;
1618 XftGlyphFontSpec *specs = xw.specbuf;
1620 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1622 for (x = x1; x < x2 && i < numspecs; x++) {
1624 if (new.mode == ATTR_WDUMMY)
1626 if (selected(x, y1))
1627 new.mode ^= ATTR_REVERSE;
1628 if (i > 0 && ATTRCMP(base, new)) {
1629 xdrawglyphfontspecs(specs, base, i, ox, y1);
1641 xdrawglyphfontspecs(specs, base, i, ox, y1);
1647 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1649 XSetForeground(xw.dpy, dc.gc,
1650 dc.col[IS_SET(MODE_REVERSE)?
1651 defaultfg : defaultbg].pixel);
1655 xximspot(int x, int y)
1657 if (xw.ime.xic == NULL)
1660 xw.ime.spot.x = borderpx + x * win.cw;
1661 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1663 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1673 visibility(XEvent *ev)
1675 XVisibilityEvent *e = &ev->xvisibility;
1677 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1683 win.mode &= ~MODE_VISIBLE;
1687 xsetpointermotion(int set)
1689 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1690 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1694 xsetmode(int set, unsigned int flags)
1696 int mode = win.mode;
1697 MODBIT(win.mode, set, flags);
1698 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1703 xsetcursor(int cursor)
1705 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
1707 win.cursor = cursor;
1712 xseturgency(int add)
1714 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1716 MODBIT(h->flags, add, XUrgencyHint);
1717 XSetWMHints(xw.dpy, xw.win, h);
1724 if (!(IS_SET(MODE_FOCUSED)))
1727 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1733 XFocusChangeEvent *e = &ev->xfocus;
1735 if (e->mode == NotifyGrab)
1738 if (ev->type == FocusIn) {
1740 XSetICFocus(xw.ime.xic);
1741 win.mode |= MODE_FOCUSED;
1743 if (IS_SET(MODE_FOCUS))
1744 ttywrite("\033[I", 3, 0);
1747 XUnsetICFocus(xw.ime.xic);
1748 win.mode &= ~MODE_FOCUSED;
1749 if (IS_SET(MODE_FOCUS))
1750 ttywrite("\033[O", 3, 0);
1755 match(uint mask, uint state)
1757 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1761 kmap(KeySym k, uint state)
1766 /* Check for mapped keys out of X11 function keys. */
1767 for (i = 0; i < LEN(mappedkeys); i++) {
1768 if (mappedkeys[i] == k)
1771 if (i == LEN(mappedkeys)) {
1772 if ((k & 0xFFFF) < 0xFD00)
1776 for (kp = key; kp < key + LEN(key); kp++) {
1780 if (!match(kp->mask, state))
1783 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1785 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1788 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1800 XKeyEvent *e = &ev->xkey;
1802 char buf[64], *customkey;
1808 if (IS_SET(MODE_KBDLOCK))
1812 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1814 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1816 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1817 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1818 bp->func(&(bp->arg));
1823 /* 2. custom keys from config.h */
1824 if ((customkey = kmap(ksym, e->state))) {
1825 ttywrite(customkey, strlen(customkey), 1);
1829 /* 3. composed string from input method */
1832 if (len == 1 && e->state & Mod1Mask) {
1833 if (IS_SET(MODE_8BIT)) {
1836 len = utf8encode(c, buf);
1844 ttywrite(buf, len, 1);
1852 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1854 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1855 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1856 win.mode |= MODE_FOCUSED;
1858 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1859 win.mode &= ~MODE_FOCUSED;
1861 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1870 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1873 cresize(e->xconfigure.width, e->xconfigure.height);
1880 int w = win.w, h = win.h;
1882 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1883 struct timespec seltv, *tv, now, lastblink, trigger;
1886 /* Waiting for window mapping */
1888 XNextEvent(xw.dpy, &ev);
1890 * This XFilterEvent call is required because of XOpenIM. It
1891 * does filter out the key event and some client message for
1892 * the input method too.
1894 if (XFilterEvent(&ev, None))
1896 if (ev.type == ConfigureNotify) {
1897 w = ev.xconfigure.width;
1898 h = ev.xconfigure.height;
1900 } while (ev.type != MapNotify);
1902 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1905 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1907 FD_SET(ttyfd, &rfd);
1910 if (XPending(xw.dpy))
1911 timeout = 0; /* existing events might not set xfd */
1913 seltv.tv_sec = timeout / 1E3;
1914 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1915 tv = timeout >= 0 ? &seltv : NULL;
1917 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1920 die("select failed: %s\n", strerror(errno));
1922 clock_gettime(CLOCK_MONOTONIC, &now);
1924 if (FD_ISSET(ttyfd, &rfd))
1928 while (XPending(xw.dpy)) {
1930 XNextEvent(xw.dpy, &ev);
1931 if (XFilterEvent(&ev, None))
1933 if (handler[ev.type])
1934 (handler[ev.type])(&ev);
1938 * To reduce flicker and tearing, when new content or event
1939 * triggers drawing, we first wait a bit to ensure we got
1940 * everything, and if nothing new arrives - we draw.
1941 * We start with trying to wait minlatency ms. If more content
1942 * arrives sooner, we retry with shorter and shorter periods,
1943 * and eventually draw even without idle after maxlatency ms.
1944 * Typically this results in low latency while interacting,
1945 * maximum latency intervals during `cat huge.txt`, and perfect
1946 * sync with periodic updates from animations/key-repeats/etc.
1948 if (FD_ISSET(ttyfd, &rfd) || xev) {
1953 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1954 / maxlatency * minlatency;
1956 continue; /* we have time, try to find idle */
1959 /* idle detected or maxlatency exhausted -> draw */
1961 if (blinktimeout && tattrset(ATTR_BLINK)) {
1962 timeout = blinktimeout - TIMEDIFF(now, lastblink);
1964 if (-timeout > blinktimeout) /* start visible */
1965 win.mode |= MODE_BLINK;
1966 win.mode ^= MODE_BLINK;
1967 tsetdirtattr(ATTR_BLINK);
1969 timeout = blinktimeout;
1980 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
1987 char fullclass[256];
1991 snprintf(fullname, sizeof(fullname), "%s.%s",
1992 opt_name ? opt_name : "st", name);
1993 snprintf(fullclass, sizeof(fullclass), "%s.%s",
1994 opt_class ? opt_class : "St", name);
1995 fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
1997 XrmGetResource(db, fullname, fullclass, &type, &ret);
1998 if (ret.addr == NULL || strncmp("String", type, 64))
2006 *idst = strtoul(ret.addr, NULL, 10);
2009 *fdst = strtof(ret.addr, NULL);
2023 resm = XResourceManagerString(xw.dpy);
2027 db = XrmGetStringDatabase(resm);
2028 for (p = resources; p < resources + LEN(resources); p++)
2029 resource_load(db, p->name, p->type, p->dst);
2035 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2036 " [-n name] [-o file]\n"
2037 " [-T title] [-t title] [-w windowid]"
2038 " [[-e] command [args ...]]\n"
2039 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2040 " [-n name] [-o file]\n"
2041 " [-T title] [-t title] [-w windowid] -l line"
2042 " [stty_args ...]\n", argv0, argv0);
2046 main(int argc, char *argv[])
2050 xsetcursor(cursorshape);
2057 opt_class = EARGF(usage());
2064 opt_font = EARGF(usage());
2067 xw.gm = XParseGeometry(EARGF(usage()),
2068 &xw.l, &xw.t, &cols, &rows);
2074 opt_io = EARGF(usage());
2077 opt_line = EARGF(usage());
2080 opt_name = EARGF(usage());
2084 opt_title = EARGF(usage());
2087 opt_embed = EARGF(usage());
2090 die("%s " VERSION "\n", argv0);
2097 if (argc > 0) /* eat all remaining arguments */
2101 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2103 setlocale(LC_CTYPE, "");
2104 XSetLocaleModifiers("");
2106 if(!(xw.dpy = XOpenDisplay(NULL)))
2107 die("Can't open display\n");
2110 cols = MAX(cols, 1);
2111 rows = MAX(rows, 1);