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>
23 #include "normalMode.h"
25 /* types used in config.h */
29 void (*func)(const Arg *);
36 void (*func)(const Arg *);
45 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
46 signed char appkey; /* application keypad */
47 signed char appcursor; /* application cursor */
50 /* Xresources preferences */
59 enum resource_type type;
64 #define XK_ANY_MOD UINT_MAX
66 #define XK_SWITCH_MOD (1<<13)
68 /* function definitions used in config.h */
69 static void clipcopy(const Arg *);
70 static void clippaste(const Arg *);
71 static void numlock(const Arg *);
72 static void selpaste(const Arg *);
73 static void zoom(const Arg *);
74 static void zoomabs(const Arg *);
75 static void zoomreset(const Arg *);
76 static void ttysend(const Arg *);
78 /* config.h for applying patches and the configuration. */
82 #define XEMBED_FOCUS_IN 4
83 #define XEMBED_FOCUS_OUT 5
86 #define IS_SET(flag) ((win.mode & (flag)) != 0)
87 #define TRUERED(x) (((x) & 0xff0000) >> 8)
88 #define TRUEGREEN(x) (((x) & 0xff00))
89 #define TRUEBLUE(x) (((x) & 0xff) << 8)
91 typedef XftDraw *Draw;
92 typedef XftColor Color;
93 typedef XftGlyphFontSpec GlyphFontSpec;
95 /* Purely graphic info */
97 int tw, th; /* tty width and height */
98 int w, h; /* window width and height */
99 int ch; /* char height */
100 int cw; /* char width */
101 int mode; /* window state/mode flags */
102 int cursor; /* cursor style */
110 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
111 Atom xembed, wmdeletewin, netwmname, netwmpid;
116 XVaNestedList spotlist;
120 XSetWindowAttributes attrs;
122 int isfixed; /* is fixed geometry? */
123 int l, t; /* left and top offset */
124 int gm; /* geometry mask */
129 char *primary, *clipboard;
130 struct timespec tclick1;
131 struct timespec tclick2;
150 /* Drawing Context */
154 Font font, bfont, ifont, ibfont;
158 static inline ushort sixd_to_16bit(int);
159 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
160 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
161 static void xdrawglyph(Glyph, int, int);
162 static void xclear(int, int, int, int);
163 static int xgeommasktogravity(int);
164 static int ximopen(Display *);
165 static void ximinstantiate(Display *, XPointer, XPointer);
166 static void ximdestroy(XIM, XPointer, XPointer);
167 static int xicdestroy(XIC, XPointer, XPointer);
168 static void xinit(int, int);
169 static void cresize(int, int);
170 static void xresize(int, int);
171 static void xhints(void);
172 static int xloadcolor(int, const char *, Color *);
173 static int xloadfont(Font *, FcPattern *);
174 static void xloadfonts(char *, double);
175 static void xunloadfont(Font *);
176 static void xunloadfonts(void);
177 static void xsetenv(void);
178 static void xseturgency(int);
179 static int evcol(XEvent *);
180 static int evrow(XEvent *);
182 static void expose(XEvent *);
183 static void visibility(XEvent *);
184 static void unmap(XEvent *);
185 static void kpress(XEvent *);
186 static void cmessage(XEvent *);
187 static void resize(XEvent *);
188 static void focus(XEvent *);
189 static uint buttonmask(uint);
190 static int mouseaction(XEvent *, uint);
191 static void brelease(XEvent *);
192 static void bpress(XEvent *);
193 static void bmotion(XEvent *);
194 static void propnotify(XEvent *);
195 static void selnotify(XEvent *);
196 static void selclear_(XEvent *);
197 static void selrequest(XEvent *);
198 static void setsel(char *, Time);
199 static void mousesel(XEvent *, int);
200 static void mousereport(XEvent *);
201 static char *kmap(KeySym, uint);
202 static int match(uint, uint);
204 static void run(void);
205 static void usage(void);
207 static void (*handler[LASTEvent])(XEvent *) = {
209 [ClientMessage] = cmessage,
210 [ConfigureNotify] = resize,
211 [VisibilityNotify] = visibility,
212 [UnmapNotify] = unmap,
216 [MotionNotify] = bmotion,
217 [ButtonPress] = bpress,
218 [ButtonRelease] = brelease,
220 * Uncomment if you want the selection to disappear when you select something
221 * different in another window.
223 /* [SelectionClear] = selclear_, */
224 [SelectionNotify] = selnotify,
226 * PropertyNotify is only turned on when there is some INCR transfer happening
227 * for the selection retrieval.
229 [PropertyNotify] = propnotify,
230 [SelectionRequest] = selrequest,
236 static XSelection xsel;
237 static TermWindow win;
239 /* Font Ring Cache */
253 /* Fontcache is an array now. A new font will be appended to the array. */
254 static Fontcache *frc = NULL;
255 static int frclen = 0;
256 static int frccap = 0;
257 static char *usedfont = NULL;
258 static double usedfontsize = 0;
259 static double defaultfontsize = 0;
261 static char *opt_class = NULL;
262 static char **opt_cmd = NULL;
263 static char *opt_embed = NULL;
264 static char *opt_font = NULL;
265 static char *opt_io = NULL;
266 static char *opt_line = NULL;
267 static char *opt_name = NULL;
268 static char *opt_title = NULL;
270 static int oldbutton = 3; /* button event on startup: 3 = release */
271 static int cursorblinks = 0;
274 clipcopy(const Arg *dummy)
278 free(xsel.clipboard);
279 xsel.clipboard = NULL;
282 if (xsel.primary != NULL) {
283 xsel.clipboard = xstrdup(xsel.primary);
284 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
285 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
290 clippaste(const Arg *dummy)
294 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
295 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
296 xw.win, CurrentTime);
300 selpaste(const Arg *dummy)
302 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
303 xw.win, CurrentTime);
307 numlock(const Arg *dummy)
309 win.mode ^= MODE_NUMLOCK;
317 larg.f = usedfontsize + arg->f;
322 zoomabs(const Arg *arg)
325 xloadfonts(usedfont, arg->f);
332 zoomreset(const Arg *arg)
336 if (defaultfontsize > 0) {
337 larg.f = defaultfontsize;
343 ttysend(const Arg *arg)
345 ttywrite(arg->s, strlen(arg->s), 1);
351 int x = e->xbutton.x - borderpx;
352 LIMIT(x, 0, win.tw - 1);
359 int y = e->xbutton.y - borderpx;
360 LIMIT(y, 0, win.th - 1);
365 mousesel(XEvent *e, int done)
367 int type, seltype = SEL_REGULAR;
368 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
370 for (type = 1; type < LEN(selmasks); ++type) {
371 if (match(selmasks[type], state)) {
376 selextend(evcol(e), evrow(e), seltype, done);
378 setsel(getsel(), e->xbutton.time);
382 mousereport(XEvent *e)
384 int len, x = evcol(e), y = evrow(e),
385 button = e->xbutton.button, state = e->xbutton.state;
390 if (e->xbutton.type == MotionNotify) {
391 if (x == ox && y == oy)
393 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
395 /* MOUSE_MOTION: no reporting if no button is pressed */
396 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
399 button = oldbutton + 32;
403 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
410 if (e->xbutton.type == ButtonPress) {
414 } else if (e->xbutton.type == ButtonRelease) {
416 /* MODE_MOUSEX10: no button release reporting */
417 if (IS_SET(MODE_MOUSEX10))
419 if (button == 64 || button == 65)
424 if (!IS_SET(MODE_MOUSEX10)) {
425 button += ((state & ShiftMask ) ? 4 : 0)
426 + ((state & Mod4Mask ) ? 8 : 0)
427 + ((state & ControlMask) ? 16 : 0);
430 if (IS_SET(MODE_MOUSESGR)) {
431 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
433 e->xbutton.type == ButtonRelease ? 'm' : 'M');
434 } else if (x < 223 && y < 223) {
435 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
436 32+button, 32+x+1, 32+y+1);
441 ttywrite(buf, len, 0);
445 buttonmask(uint button)
447 return button == Button1 ? Button1Mask
448 : button == Button2 ? Button2Mask
449 : button == Button3 ? Button3Mask
450 : button == Button4 ? Button4Mask
451 : button == Button5 ? Button5Mask
456 mouseaction(XEvent *e, uint release)
460 /* ignore Button<N>mask for Button<N> - it's set on release */
461 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
463 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
464 if (ms->release == release &&
465 ms->button == e->xbutton.button &&
466 (match(ms->mod, state) || /* exact or forced */
467 match(ms->mod, state & ~forcemousemod))) {
468 ms->func(&(ms->arg));
482 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
487 if (mouseaction(e, 0))
490 if (e->xbutton.button == Button1) {
492 * If the user clicks below predefined timeouts specific
493 * snapping behaviour is exposed.
495 clock_gettime(CLOCK_MONOTONIC, &now);
496 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
498 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
503 xsel.tclick2 = xsel.tclick1;
506 selstart(evcol(e), evrow(e), snap);
511 propnotify(XEvent *e)
513 XPropertyEvent *xpev;
514 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
516 xpev = &e->xproperty;
517 if (xpev->state == PropertyNewValue &&
518 (xpev->atom == XA_PRIMARY ||
519 xpev->atom == clipboard)) {
527 ulong nitems, ofs, rem;
529 uchar *data, *last, *repl;
530 Atom type, incratom, property = None;
532 incratom = XInternAtom(xw.dpy, "INCR", 0);
535 if (e->type == SelectionNotify)
536 property = e->xselection.property;
537 else if (e->type == PropertyNotify)
538 property = e->xproperty.atom;
540 if (property == None)
544 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
545 BUFSIZ/4, False, AnyPropertyType,
546 &type, &format, &nitems, &rem,
548 fprintf(stderr, "Clipboard allocation failed\n");
552 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
554 * If there is some PropertyNotify with no data, then
555 * this is the signal of the selection owner that all
556 * data has been transferred. We won't need to receive
557 * PropertyNotify events anymore.
559 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
560 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
564 if (type == incratom) {
566 * Activate the PropertyNotify events so we receive
567 * when the selection owner does send us the next
570 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
571 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
575 * Deleting the property is the transfer start signal.
577 XDeleteProperty(xw.dpy, xw.win, (int)property);
583 * Line endings are inconsistent in the terminal and GUI world
584 * copy and pasting. When receiving some selection data,
585 * replace all '\n' with '\r'.
586 * FIXME: Fix the computer world.
589 last = data + nitems * format / 8;
590 while ((repl = memchr(repl, '\n', last - repl))) {
594 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
595 ttywrite("\033[200~", 6, 0);
596 ttywrite((char *)data, nitems * format / 8, 1);
597 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
598 ttywrite("\033[201~", 6, 0);
600 /* number of 32-bit chunks returned */
601 ofs += nitems * format / 32;
605 * Deleting the property again tells the selection owner to send the
606 * next data chunk in the property.
608 XDeleteProperty(xw.dpy, xw.win, (int)property);
624 selrequest(XEvent *e)
626 XSelectionRequestEvent *xsre;
628 Atom xa_targets, string, clipboard;
631 xsre = (XSelectionRequestEvent *) e;
632 xev.type = SelectionNotify;
633 xev.requestor = xsre->requestor;
634 xev.selection = xsre->selection;
635 xev.target = xsre->target;
636 xev.time = xsre->time;
637 if (xsre->property == None)
638 xsre->property = xsre->target;
643 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
644 if (xsre->target == xa_targets) {
645 /* respond with the supported type */
646 string = xsel.xtarget;
647 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
648 XA_ATOM, 32, PropModeReplace,
649 (uchar *) &string, 1);
650 xev.property = xsre->property;
651 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
653 * xith XA_STRING non ascii characters may be incorrect in the
654 * requestor. It is not our problem, use utf8.
656 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
657 if (xsre->selection == XA_PRIMARY) {
658 seltext = xsel.primary;
659 } else if (xsre->selection == clipboard) {
660 seltext = xsel.clipboard;
663 "Unhandled clipboard selection 0x%lx\n",
667 if (seltext != NULL) {
668 XChangeProperty(xsre->display, xsre->requestor,
669 xsre->property, xsre->target,
671 (uchar *)seltext, strlen(seltext));
672 xev.property = xsre->property;
676 /* all done, send a notification to the listener */
677 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
678 fprintf(stderr, "Error sending SelectionNotify event\n");
682 setsel(char *str, Time t)
690 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
691 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
698 setsel(str, CurrentTime);
704 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
709 if (mouseaction(e, 1))
711 if (e->xbutton.button == Button1)
718 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
727 cresize(int width, int height)
736 col = (win.w - 2 * borderpx) / win.cw;
737 row = (win.h - 2 * borderpx) / win.ch;
743 ttyresize(win.tw, win.th);
747 xresize(int col, int row)
749 win.tw = col * win.cw;
750 win.th = row * win.ch;
752 XFreePixmap(xw.dpy, xw.buf);
753 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
754 DefaultDepth(xw.dpy, xw.scr));
755 XftDrawChange(xw.draw, xw.buf);
756 xclear(0, 0, win.w, win.h);
758 /* resize to new width */
759 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
765 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
769 xloadcolor(int i, const char *name, Color *ncolor)
771 XRenderColor color = { .alpha = 0xffff };
774 if (BETWEEN(i, 16, 255)) { /* 256 color */
775 if (i < 6*6*6+16) { /* same colors as xterm */
776 color.red = sixd_to_16bit( ((i-16)/36)%6 );
777 color.green = sixd_to_16bit( ((i-16)/6) %6 );
778 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
779 } else { /* greyscale */
780 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
781 color.green = color.blue = color.red;
783 return XftColorAllocValue(xw.dpy, xw.vis,
784 xw.cmap, &color, ncolor);
789 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
792 void normalMode() { historyModeToggle((win.mode ^=MODE_NORMAL) & MODE_NORMAL); }
802 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
803 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
805 dc.collen = MAX(LEN(colorname), 256);
806 dc.col = xmalloc(dc.collen * sizeof(Color));
809 for (i = 0; i < dc.collen; i++)
810 if (!xloadcolor(i, NULL, &dc.col[i])) {
812 die("could not allocate color '%s'\n", colorname[i]);
814 die("could not allocate color %d\n", i);
820 xsetcolorname(int x, const char *name)
824 if (!BETWEEN(x, 0, dc.collen))
827 if (!xloadcolor(x, name, &ncolor))
830 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
837 * Absolute coordinates.
840 xclear(int x1, int y1, int x2, int y2)
843 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
844 x1, y1, x2-x1, y2-y1);
850 XClassHint class = {opt_name ? opt_name : "st",
851 opt_class ? opt_class : "St"};
852 XWMHints wm = {.flags = InputHint, .input = 1};
855 sizeh = XAllocSizeHints();
857 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
858 sizeh->height = win.h;
859 sizeh->width = win.w;
860 sizeh->height_inc = win.ch;
861 sizeh->width_inc = win.cw;
862 sizeh->base_height = 2 * borderpx;
863 sizeh->base_width = 2 * borderpx;
864 sizeh->min_height = win.ch + 2 * borderpx;
865 sizeh->min_width = win.cw + 2 * borderpx;
867 sizeh->flags |= PMaxSize;
868 sizeh->min_width = sizeh->max_width = win.w;
869 sizeh->min_height = sizeh->max_height = win.h;
871 if (xw.gm & (XValue|YValue)) {
872 sizeh->flags |= USPosition | PWinGravity;
875 sizeh->win_gravity = xgeommasktogravity(xw.gm);
878 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
884 xgeommasktogravity(int mask)
886 switch (mask & (XNegative|YNegative)) {
888 return NorthWestGravity;
890 return NorthEastGravity;
892 return SouthWestGravity;
895 return SouthEastGravity;
899 xloadfont(Font *f, FcPattern *pattern)
901 FcPattern *configured;
905 int wantattr, haveattr;
908 * Manually configure instead of calling XftMatchFont
909 * so that we can use the configured pattern for
910 * "missing glyph" lookups.
912 configured = FcPatternDuplicate(pattern);
916 FcConfigSubstitute(NULL, configured, FcMatchPattern);
917 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
919 match = FcFontMatch(NULL, configured, &result);
921 FcPatternDestroy(configured);
925 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
926 FcPatternDestroy(configured);
927 FcPatternDestroy(match);
931 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
934 * Check if xft was unable to find a font with the appropriate
935 * slant but gave us one anyway. Try to mitigate.
937 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
938 &haveattr) != XftResultMatch) || haveattr < wantattr) {
940 fputs("font slant does not match\n", stderr);
944 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
946 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
947 &haveattr) != XftResultMatch) || haveattr != wantattr) {
949 fputs("font weight does not match\n", stderr);
953 XftTextExtentsUtf8(xw.dpy, f->match,
954 (const FcChar8 *) ascii_printable,
955 strlen(ascii_printable), &extents);
958 f->pattern = configured;
960 f->ascent = f->match->ascent;
961 f->descent = f->match->descent;
963 f->rbearing = f->match->max_advance_width;
965 f->height = f->ascent + f->descent;
966 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
972 xloadfonts(char *fontstr, double fontsize)
977 if (fontstr[0] == '-')
978 pattern = XftXlfdParse(fontstr, False, False);
980 pattern = FcNameParse((FcChar8 *)fontstr);
983 die("can't open font %s\n", fontstr);
986 FcPatternDel(pattern, FC_PIXEL_SIZE);
987 FcPatternDel(pattern, FC_SIZE);
988 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
989 usedfontsize = fontsize;
991 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
993 usedfontsize = fontval;
994 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
999 * Default font size is 12, if none given. This is to
1000 * have a known usedfontsize value.
1002 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1005 defaultfontsize = usedfontsize;
1008 if (xloadfont(&dc.font, pattern))
1009 die("can't open font %s\n", fontstr);
1011 if (usedfontsize < 0) {
1012 FcPatternGetDouble(dc.font.match->pattern,
1013 FC_PIXEL_SIZE, 0, &fontval);
1014 usedfontsize = fontval;
1016 defaultfontsize = fontval;
1019 /* Setting character width and height. */
1020 win.cw = ceilf(dc.font.width * cwscale);
1021 win.ch = ceilf(dc.font.height * chscale);
1023 FcPatternDel(pattern, FC_SLANT);
1024 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1025 if (xloadfont(&dc.ifont, pattern))
1026 die("can't open font %s\n", fontstr);
1028 FcPatternDel(pattern, FC_WEIGHT);
1029 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1030 if (xloadfont(&dc.ibfont, pattern))
1031 die("can't open font %s\n", fontstr);
1033 FcPatternDel(pattern, FC_SLANT);
1034 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1035 if (xloadfont(&dc.bfont, pattern))
1036 die("can't open font %s\n", fontstr);
1038 FcPatternDestroy(pattern);
1042 xunloadfont(Font *f)
1044 XftFontClose(xw.dpy, f->match);
1045 FcPatternDestroy(f->pattern);
1047 FcFontSetDestroy(f->set);
1053 /* Free the loaded fonts in the font cache. */
1055 XftFontClose(xw.dpy, frc[--frclen].font);
1057 xunloadfont(&dc.font);
1058 xunloadfont(&dc.bfont);
1059 xunloadfont(&dc.ifont);
1060 xunloadfont(&dc.ibfont);
1064 ximopen(Display *dpy)
1066 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1067 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1069 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1070 if (xw.ime.xim == NULL)
1073 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1074 fprintf(stderr, "XSetIMValues: "
1075 "Could not set XNDestroyCallback.\n");
1077 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1080 if (xw.ime.xic == NULL) {
1081 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1082 XIMPreeditNothing | XIMStatusNothing,
1083 XNClientWindow, xw.win,
1084 XNDestroyCallback, &icdestroy,
1087 if (xw.ime.xic == NULL)
1088 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1094 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1097 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1098 ximinstantiate, NULL);
1102 ximdestroy(XIM xim, XPointer client, XPointer call)
1105 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1106 ximinstantiate, NULL);
1107 XFree(xw.ime.spotlist);
1111 xicdestroy(XIC xim, XPointer client, XPointer call)
1118 xinit(int cols, int rows)
1123 pid_t thispid = getpid();
1124 XColor xmousefg, xmousebg;
1126 xw.scr = XDefaultScreen(xw.dpy);
1127 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1131 die("could not init fontconfig.\n");
1133 usedfont = (opt_font == NULL)? font : opt_font;
1134 xloadfonts(usedfont, 0);
1137 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1140 /* adjust fixed window geometry */
1141 win.w = 2 * borderpx + cols * win.cw;
1142 win.h = 2 * borderpx + rows * win.ch;
1143 if (xw.gm & XNegative)
1144 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1145 if (xw.gm & YNegative)
1146 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1149 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1150 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1151 xw.attrs.bit_gravity = NorthWestGravity;
1152 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1153 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1154 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1155 xw.attrs.colormap = xw.cmap;
1157 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1158 parent = XRootWindow(xw.dpy, xw.scr);
1159 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1160 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1161 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1162 | CWEventMask | CWColormap, &xw.attrs);
1164 memset(&gcvalues, 0, sizeof(gcvalues));
1165 gcvalues.graphics_exposures = False;
1166 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1168 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1169 DefaultDepth(xw.dpy, xw.scr));
1170 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1171 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1173 /* font spec buffer */
1174 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1176 /* Xft rendering context */
1177 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1180 if (!ximopen(xw.dpy)) {
1181 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1182 ximinstantiate, NULL);
1185 /* white cursor, black outline */
1186 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1187 XDefineCursor(xw.dpy, xw.win, cursor);
1189 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1190 xmousefg.red = 0xffff;
1191 xmousefg.green = 0xffff;
1192 xmousefg.blue = 0xffff;
1195 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1196 xmousebg.red = 0x0000;
1197 xmousebg.green = 0x0000;
1198 xmousebg.blue = 0x0000;
1201 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1203 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1204 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1205 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1206 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1208 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1209 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1210 PropModeReplace, (uchar *)&thispid, 1);
1212 win.mode = MODE_NUMLOCK;
1215 XMapWindow(xw.dpy, xw.win);
1216 XSync(xw.dpy, False);
1218 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1219 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1220 xsel.primary = NULL;
1221 xsel.clipboard = NULL;
1222 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1223 if (xsel.xtarget == None)
1224 xsel.xtarget = XA_STRING;
1228 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1230 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1231 ushort mode, prevmode = USHRT_MAX;
1232 Font *font = &dc.font;
1233 int frcflags = FRC_NORMAL;
1234 float runewidth = win.cw;
1238 FcPattern *fcpattern, *fontpattern;
1239 FcFontSet *fcsets[] = { NULL };
1240 FcCharSet *fccharset;
1241 int i, f, numspecs = 0;
1243 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1244 /* Fetch rune and mode for current glyph. */
1245 Glyph g = glyphs[i];
1246 historyOverlay(x+i, y, &g);
1250 /* Skip dummy wide-character spacing. */
1251 if (mode == ATTR_WDUMMY)
1254 /* Determine font for glyph if different from previous glyph. */
1255 if (prevmode != mode) {
1258 frcflags = FRC_NORMAL;
1259 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1260 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1262 frcflags = FRC_ITALICBOLD;
1263 } else if (mode & ATTR_ITALIC) {
1265 frcflags = FRC_ITALIC;
1266 } else if (mode & ATTR_BOLD) {
1268 frcflags = FRC_BOLD;
1270 yp = winy + font->ascent;
1273 /* Lookup character index with default font. */
1274 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1276 specs[numspecs].font = font->match;
1277 specs[numspecs].glyph = glyphidx;
1278 specs[numspecs].x = (short)xp;
1279 specs[numspecs].y = (short)yp;
1285 /* Fallback on font cache, search the font cache for match. */
1286 for (f = 0; f < frclen; f++) {
1287 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1288 /* Everything correct. */
1289 if (glyphidx && frc[f].flags == frcflags)
1291 /* We got a default font for a not found glyph. */
1292 if (!glyphidx && frc[f].flags == frcflags
1293 && frc[f].unicodep == rune) {
1298 /* Nothing was found. Use fontconfig to find matching font. */
1301 font->set = FcFontSort(0, font->pattern,
1303 fcsets[0] = font->set;
1306 * Nothing was found in the cache. Now use
1307 * some dozen of Fontconfig calls to get the
1308 * font for one single character.
1310 * Xft and fontconfig are design failures.
1312 fcpattern = FcPatternDuplicate(font->pattern);
1313 fccharset = FcCharSetCreate();
1315 FcCharSetAddChar(fccharset, rune);
1316 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1318 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1320 FcConfigSubstitute(0, fcpattern,
1322 FcDefaultSubstitute(fcpattern);
1324 fontpattern = FcFontSetMatch(0, fcsets, 1,
1327 /* Allocate memory for the new cache entry. */
1328 if (frclen >= frccap) {
1330 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1333 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1335 if (!frc[frclen].font)
1336 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1338 frc[frclen].flags = frcflags;
1339 frc[frclen].unicodep = rune;
1341 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1346 FcPatternDestroy(fcpattern);
1347 FcCharSetDestroy(fccharset);
1350 specs[numspecs].font = frc[f].font;
1351 specs[numspecs].glyph = glyphidx;
1352 specs[numspecs].x = (short)xp;
1353 specs[numspecs].y = (short)yp;
1362 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1364 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1365 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1366 width = charlen * win.cw;
1367 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1368 XRenderColor colfg, colbg;
1371 /* Fallback on color display for attributes not supported by the font */
1372 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1373 if (dc.ibfont.badslant || dc.ibfont.badweight)
1374 base.fg = defaultattr;
1375 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1376 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1377 base.fg = defaultattr;
1380 if (IS_TRUECOL(base.fg)) {
1381 colfg.alpha = 0xffff;
1382 colfg.red = TRUERED(base.fg);
1383 colfg.green = TRUEGREEN(base.fg);
1384 colfg.blue = TRUEBLUE(base.fg);
1385 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1388 fg = &dc.col[base.fg];
1391 if (IS_TRUECOL(base.bg)) {
1392 colbg.alpha = 0xffff;
1393 colbg.green = TRUEGREEN(base.bg);
1394 colbg.red = TRUERED(base.bg);
1395 colbg.blue = TRUEBLUE(base.bg);
1396 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1399 bg = &dc.col[base.bg];
1402 /* Change basic system colors [0-7] to bright system colors [8-15] */
1403 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1404 fg = &dc.col[base.fg + 8];
1406 if (IS_SET(MODE_REVERSE)) {
1407 if (fg == &dc.col[defaultfg]) {
1408 fg = &dc.col[defaultbg];
1410 colfg.red = ~fg->color.red;
1411 colfg.green = ~fg->color.green;
1412 colfg.blue = ~fg->color.blue;
1413 colfg.alpha = fg->color.alpha;
1414 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1419 if (bg == &dc.col[defaultbg]) {
1420 bg = &dc.col[defaultfg];
1422 colbg.red = ~bg->color.red;
1423 colbg.green = ~bg->color.green;
1424 colbg.blue = ~bg->color.blue;
1425 colbg.alpha = bg->color.alpha;
1426 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1432 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1433 colfg.red = fg->color.red / 2;
1434 colfg.green = fg->color.green / 2;
1435 colfg.blue = fg->color.blue / 2;
1436 colfg.alpha = fg->color.alpha;
1437 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1441 if (base.mode & ATTR_REVERSE) {
1447 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1450 if (base.mode & ATTR_INVISIBLE)
1453 /* Intelligent cleaning up of the borders. */
1455 xclear(0, (y == 0)? 0 : winy, borderpx,
1457 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1459 if (winx + width >= borderpx + win.tw) {
1460 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1461 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1464 xclear(winx, 0, winx + width, borderpx);
1465 if (winy + win.ch >= borderpx + win.th)
1466 xclear(winx, winy + win.ch, winx + width, win.h);
1468 /* Clean up the region we want to draw to. */
1469 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1471 /* Set the clip region because Xft is sometimes dirty. */
1476 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1478 /* Render the glyphs. */
1479 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1481 /* Render underline and strikethrough. */
1482 if (base.mode & ATTR_UNDERLINE) {
1483 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1487 if (base.mode & ATTR_STRUCK) {
1488 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1492 /* Reset clip to none. */
1493 XftDrawSetClip(xw.draw, 0);
1497 xdrawglyph(Glyph g, int x, int y)
1500 XftGlyphFontSpec spec;
1502 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1503 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1507 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1511 /* remove the old cursor */
1512 if (selected(ox, oy))
1513 og.mode ^= ATTR_REVERSE;
1514 xdrawglyph(og, ox, oy);
1516 if (IS_SET(MODE_HIDE))
1520 * Select the right color for the right mode.
1522 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1524 if (IS_SET(MODE_REVERSE)) {
1525 g.mode |= ATTR_REVERSE;
1527 if (selected(cx, cy)) {
1528 drawcol = dc.col[defaultcs];
1531 drawcol = dc.col[defaultrcs];
1535 if (selected(cx, cy)) {
1542 drawcol = dc.col[g.bg];
1545 /* draw the new one */
1546 if (IS_SET(MODE_FOCUSED)) {
1547 switch (win.cursor) {
1548 case 0: /* Blinking block */
1549 case 1: /* Blinking block (default) */
1550 if (IS_SET(MODE_BLINK))
1553 case 2: /* Steady block */
1554 xdrawglyph(g, cx, cy);
1556 case 3: /* Blinking underline */
1557 if (IS_SET(MODE_BLINK))
1560 case 4: /* Steady underline */
1561 XftDrawRect(xw.draw, &drawcol,
1562 borderpx + cx * win.cw,
1563 borderpx + (cy + 1) * win.ch - \
1565 win.cw, cursorthickness);
1567 case 5: /* Blinking bar */
1568 if (IS_SET(MODE_BLINK))
1571 case 6: /* Steady bar */
1572 XftDrawRect(xw.draw, &drawcol,
1573 borderpx + cx * win.cw,
1574 borderpx + cy * win.ch,
1575 cursorthickness, win.ch);
1577 case 7: /* Blinking st cursor */
1578 if (IS_SET(MODE_BLINK))
1581 case 8: /* Steady st cursor */
1583 xdrawglyph(g, cx, cy);
1587 XftDrawRect(xw.draw, &drawcol,
1588 borderpx + cx * win.cw,
1589 borderpx + cy * win.ch,
1591 XftDrawRect(xw.draw, &drawcol,
1592 borderpx + cx * win.cw,
1593 borderpx + cy * win.ch,
1595 XftDrawRect(xw.draw, &drawcol,
1596 borderpx + (cx + 1) * win.cw - 1,
1597 borderpx + cy * win.ch,
1599 XftDrawRect(xw.draw, &drawcol,
1600 borderpx + cx * win.cw,
1601 borderpx + (cy + 1) * win.ch - 1,
1609 char buf[sizeof(long) * 8 + 1];
1611 snprintf(buf, sizeof(buf), "%lu", xw.win);
1612 setenv("WINDOWID", buf, 1);
1619 DEFAULT(p, opt_title);
1621 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1623 XSetWMName(xw.dpy, xw.win, &prop);
1624 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1631 if (IS_SET(MODE_VISIBLE))
1632 XCopyArea(xw.dpy, xw.win, xw.buf, dc.gc, 0, 0, win.w, win.h, 0, 0);
1633 return IS_SET(MODE_VISIBLE);
1637 xdrawline(Line line, int x1, int y1, int x2)
1639 int i, x, ox, numspecs;
1641 XftGlyphFontSpec *specs = xw.specbuf;
1643 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1645 for (x = x1; x < x2 && i < numspecs; x++) {
1647 historyOverlay(x, y1, &new);
1648 if (new.mode == ATTR_WDUMMY)
1650 if (selected(x, y1))
1651 new.mode ^= ATTR_REVERSE;
1652 if (i > 0 && ATTRCMP(base, new)) {
1653 xdrawglyphfontspecs(specs, base, i, ox, y1);
1665 xdrawglyphfontspecs(specs, base, i, ox, y1);
1671 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1673 XSetForeground(xw.dpy, dc.gc,
1674 dc.col[IS_SET(MODE_REVERSE)?
1675 defaultfg : defaultbg].pixel);
1679 xximspot(int x, int y)
1681 if (xw.ime.xic == NULL)
1684 xw.ime.spot.x = borderpx + x * win.cw;
1685 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1687 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1697 visibility(XEvent *ev)
1699 XVisibilityEvent *e = &ev->xvisibility;
1701 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1707 win.mode &= ~MODE_VISIBLE;
1711 xsetpointermotion(int set)
1713 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1714 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1718 xsetmode(int set, unsigned int flags)
1720 int mode = win.mode;
1721 MODBIT(win.mode, set, flags);
1722 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1727 xsetcursor(int cursor)
1729 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1731 win.cursor = cursor;
1732 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1733 win.cursor == 3 || win.cursor == 5 ||
1739 xseturgency(int add)
1741 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1743 MODBIT(h->flags, add, XUrgencyHint);
1744 XSetWMHints(xw.dpy, xw.win, h);
1751 if (!(IS_SET(MODE_FOCUSED)))
1754 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1760 XFocusChangeEvent *e = &ev->xfocus;
1762 if (e->mode == NotifyGrab)
1765 if (ev->type == FocusIn) {
1767 XSetICFocus(xw.ime.xic);
1768 win.mode |= MODE_FOCUSED;
1770 if (IS_SET(MODE_FOCUS))
1771 ttywrite("\033[I", 3, 0);
1774 XUnsetICFocus(xw.ime.xic);
1775 win.mode &= ~MODE_FOCUSED;
1776 if (IS_SET(MODE_FOCUS))
1777 ttywrite("\033[O", 3, 0);
1782 match(uint mask, uint state)
1784 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1788 kmap(KeySym k, uint state)
1793 /* Check for mapped keys out of X11 function keys. */
1794 for (i = 0; i < LEN(mappedkeys); i++) {
1795 if (mappedkeys[i] == k)
1798 if (i == LEN(mappedkeys)) {
1799 if ((k & 0xFFFF) < 0xFD00)
1803 for (kp = key; kp < key + LEN(key); kp++) {
1807 if (!match(kp->mask, state))
1810 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1812 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1815 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1827 XKeyEvent *e = &ev->xkey;
1829 char buf[64], *customkey;
1835 if (IS_SET(MODE_KBDLOCK))
1839 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1841 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1842 if (IS_SET(MODE_NORMAL)) {
1843 if (kpressHist(buf, len, match(ControlMask, e->state), &ksym)
1844 == finished) normalMode();
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;
2016 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2023 char fullclass[256];
2027 snprintf(fullname, sizeof(fullname), "%s.%s",
2028 opt_name ? opt_name : "st", name);
2029 snprintf(fullclass, sizeof(fullclass), "%s.%s",
2030 opt_class ? opt_class : "St", name);
2031 fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
2033 XrmGetResource(db, fullname, fullclass, &type, &ret);
2034 if (ret.addr == NULL || strncmp("String", type, 64))
2042 *idst = strtoul(ret.addr, NULL, 10);
2045 *fdst = strtof(ret.addr, NULL);
2059 resm = XResourceManagerString(xw.dpy);
2063 db = XrmGetStringDatabase(resm);
2064 for (p = resources; p < resources + LEN(resources); p++)
2065 resource_load(db, p->name, p->type, p->dst);
2071 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2072 " [-n name] [-o file]\n"
2073 " [-T title] [-t title] [-w windowid]"
2074 " [[-e] command [args ...]]\n"
2075 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2076 " [-n name] [-o file]\n"
2077 " [-T title] [-t title] [-w windowid] -l line"
2078 " [stty_args ...]\n", argv0, argv0);
2082 main(int argc, char *argv[])
2086 xsetcursor(cursorstyle);
2093 opt_class = EARGF(usage());
2100 opt_font = EARGF(usage());
2103 xw.gm = XParseGeometry(EARGF(usage()),
2104 &xw.l, &xw.t, &cols, &rows);
2110 opt_io = EARGF(usage());
2113 opt_line = EARGF(usage());
2116 opt_name = EARGF(usage());
2120 opt_title = EARGF(usage());
2123 opt_embed = EARGF(usage());
2126 die("%s " VERSION "\n", argv0);
2133 if (argc > 0) /* eat all remaining arguments */
2137 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2139 setlocale(LC_CTYPE, "");
2140 XSetLocaleModifiers("");
2142 if(!(xw.dpy = XOpenDisplay(NULL)))
2143 die("Can't open display\n");
2146 cols = MAX(cols, 1);
2147 rows = MAX(rows, 1);