1 /* See LICENSE for license details. */
7 #include <sys/select.h>
12 #include <X11/Xatom.h>
14 #include <X11/cursorfont.h>
15 #include <X11/keysym.h>
16 #include <X11/Xft/Xft.h>
17 #include <X11/XKBlib.h>
18 #include <X11/Xresource.h>
24 #include "normalMode.h"
26 /* types used in config.h */
30 void (*func)(const Arg *);
37 void (*func)(const Arg *);
46 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
47 signed char appkey; /* application keypad */
48 signed char appcursor; /* application cursor */
51 /* Xresources preferences */
60 enum resource_type type;
65 #define XK_ANY_MOD UINT_MAX
67 #define XK_SWITCH_MOD (1<<13)
69 /* function definitions used in config.h */
70 static void clipcopy(const Arg *);
71 static void clippaste(const Arg *);
72 static void numlock(const Arg *);
73 static void selpaste(const Arg *);
74 static void zoom(const Arg *);
75 static void zoomabs(const Arg *);
76 static void zoomreset(const Arg *);
77 static void ttysend(const Arg *);
78 static void plumber(const Arg *);
80 /* config.h for applying patches and the configuration. */
84 #define XEMBED_FOCUS_IN 4
85 #define XEMBED_FOCUS_OUT 5
88 #define IS_SET(flag) ((win.mode & (flag)) != 0)
89 #define TRUERED(x) (((x) & 0xff0000) >> 8)
90 #define TRUEGREEN(x) (((x) & 0xff00))
91 #define TRUEBLUE(x) (((x) & 0xff) << 8)
93 typedef XftDraw *Draw;
94 typedef XftColor Color;
95 typedef XftGlyphFontSpec GlyphFontSpec;
97 /* Purely graphic info */
99 int tw, th; /* tty width and height */
100 int w, h; /* window width and height */
101 int ch; /* char height */
102 int cw; /* char width */
103 int mode; /* window state/mode flags */
104 int cursor; /* cursor style */
112 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
113 Atom xembed, wmdeletewin, netwmname, netwmpid;
118 XVaNestedList spotlist;
122 XSetWindowAttributes attrs;
124 int isfixed; /* is fixed geometry? */
125 int l, t; /* left and top offset */
126 int gm; /* geometry mask */
131 char *primary, *clipboard;
132 struct timespec tclick1;
133 struct timespec tclick2;
152 /* Drawing Context */
156 Font font, bfont, ifont, ibfont;
160 static inline ushort sixd_to_16bit(int);
161 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
162 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
163 static void xdrawglyph(Glyph, int, int);
164 static void xclear(int, int, int, int);
165 static int xgeommasktogravity(int);
166 static int ximopen(Display *);
167 static void ximinstantiate(Display *, XPointer, XPointer);
168 static void ximdestroy(XIM, XPointer, XPointer);
169 static int xicdestroy(XIC, XPointer, XPointer);
170 static void xinit(int, int);
171 static void cresize(int, int);
172 static void xresize(int, int);
173 static void xhints(void);
174 static int xloadcolor(int, const char *, Color *);
175 static int xloadfont(Font *, FcPattern *);
176 static void xloadfonts(char *, double);
177 static void xunloadfont(Font *);
178 static void xunloadfonts(void);
179 static void xsetenv(void);
180 static void xseturgency(int);
181 static int evcol(XEvent *);
182 static int evrow(XEvent *);
184 static void expose(XEvent *);
185 static void visibility(XEvent *);
186 static void unmap(XEvent *);
187 static void kpress(XEvent *);
188 static void cmessage(XEvent *);
189 static void resize(XEvent *);
190 static void focus(XEvent *);
191 static uint buttonmask(uint);
192 static int mouseaction(XEvent *, uint);
193 static void brelease(XEvent *);
194 static void bpress(XEvent *);
195 static void bmotion(XEvent *);
196 static void propnotify(XEvent *);
197 static void selnotify(XEvent *);
198 static void selclear_(XEvent *);
199 static void selrequest(XEvent *);
200 static void setsel(char *, Time);
201 static void plumb(char *sel);
202 static void mousesel(XEvent *, int);
203 static void mousereport(XEvent *);
204 static char *kmap(KeySym, uint);
205 static int match(uint, uint);
208 static void run(void);
209 static void usage(void);
211 static void (*handler[LASTEvent])(XEvent *) = {
213 [ClientMessage] = cmessage,
214 [ConfigureNotify] = resize,
215 [VisibilityNotify] = visibility,
216 [UnmapNotify] = unmap,
220 [MotionNotify] = bmotion,
221 [ButtonPress] = bpress,
222 [ButtonRelease] = brelease,
224 * Uncomment if you want the selection to disappear when you select something
225 * different in another window.
227 /* [SelectionClear] = selclear_, */
228 [SelectionNotify] = selnotify,
230 * PropertyNotify is only turned on when there is some INCR transfer happening
231 * for the selection retrieval.
233 [PropertyNotify] = propnotify,
234 [SelectionRequest] = selrequest,
241 static XSelection xsel;
242 static TermWindow win;
244 /* Font Ring Cache */
258 /* Fontcache is an array now. A new font will be appended to the array. */
259 static Fontcache *frc = NULL;
260 static int frclen = 0;
261 static int frccap = 0;
262 static char *usedfont = NULL;
263 static double usedfontsize = 0;
264 static double defaultfontsize = 0;
266 static char *opt_class = NULL;
267 static char **opt_cmd = NULL;
268 static char *opt_embed = NULL;
269 static char *opt_font = NULL;
270 static char *opt_io = NULL;
271 static char *opt_line = NULL;
272 static char *opt_name = NULL;
273 static char *opt_title = NULL;
275 static int oldbutton = 3; /* button event on startup: 3 = release */
276 static int cursorblinks = 0;
279 clipcopy(const Arg *dummy)
283 free(xsel.clipboard);
284 xsel.clipboard = NULL;
287 if (xsel.primary != NULL) {
288 xsel.clipboard = xstrdup(xsel.primary);
289 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
290 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
295 clippaste(const Arg *dummy)
299 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
300 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
301 xw.win, CurrentTime);
305 selpaste(const Arg *dummy)
307 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
308 xw.win, CurrentTime);
312 numlock(const Arg *dummy)
314 win.mode ^= MODE_NUMLOCK;
322 larg.f = usedfontsize + arg->f;
327 zoomabs(const Arg *arg)
330 xloadfonts(usedfont, arg->f);
337 zoomreset(const Arg *arg)
341 if (defaultfontsize > 0) {
342 larg.f = defaultfontsize;
348 ttysend(const Arg *arg)
350 ttywrite(arg->s, strlen(arg->s), 1);
354 plumber(const Arg *arg)
362 int x = e->xbutton.x - borderpx;
363 LIMIT(x, 0, win.tw - 1);
370 int y = e->xbutton.y - borderpx;
371 LIMIT(y, 0, win.th - 1);
376 mousesel(XEvent *e, int done)
378 int type, seltype = SEL_REGULAR;
379 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
381 for (type = 1; type < LEN(selmasks); ++type) {
382 if (match(selmasks[type], state)) {
387 selextend(evcol(e), evrow(e), seltype, done);
389 setsel(getsel(), e->xbutton.time);
393 mousereport(XEvent *e)
395 int len, x = evcol(e), y = evrow(e),
396 button = e->xbutton.button, state = e->xbutton.state;
401 if (e->xbutton.type == MotionNotify) {
402 if (x == ox && y == oy)
404 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
406 /* MOUSE_MOTION: no reporting if no button is pressed */
407 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
410 button = oldbutton + 32;
414 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
421 if (e->xbutton.type == ButtonPress) {
425 } else if (e->xbutton.type == ButtonRelease) {
427 /* MODE_MOUSEX10: no button release reporting */
428 if (IS_SET(MODE_MOUSEX10))
430 if (button == 64 || button == 65)
435 if (!IS_SET(MODE_MOUSEX10)) {
436 button += ((state & ShiftMask ) ? 4 : 0)
437 + ((state & Mod4Mask ) ? 8 : 0)
438 + ((state & ControlMask) ? 16 : 0);
441 if (IS_SET(MODE_MOUSESGR)) {
442 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
444 e->xbutton.type == ButtonRelease ? 'm' : 'M');
445 } else if (x < 223 && y < 223) {
446 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
447 32+button, 32+x+1, 32+y+1);
452 ttywrite(buf, len, 0);
456 buttonmask(uint button)
458 return button == Button1 ? Button1Mask
459 : button == Button2 ? Button2Mask
460 : button == Button3 ? Button3Mask
461 : button == Button4 ? Button4Mask
462 : button == Button5 ? Button5Mask
467 mouseaction(XEvent *e, uint release)
471 /* ignore Button<N>mask for Button<N> - it's set on release */
472 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
474 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
475 if (ms->release == release &&
476 ms->button == e->xbutton.button &&
477 (match(ms->mod, state) || /* exact or forced */
478 match(ms->mod, state & ~forcemousemod))) {
479 ms->func(&(ms->arg));
493 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
498 if (mouseaction(e, 0))
501 if (e->xbutton.button == Button1) {
503 * If the user clicks below predefined timeouts specific
504 * snapping behaviour is exposed.
506 clock_gettime(CLOCK_MONOTONIC, &now);
507 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
509 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
514 xsel.tclick2 = xsel.tclick1;
517 selstart(evcol(e), evrow(e), snap);
522 propnotify(XEvent *e)
524 XPropertyEvent *xpev;
525 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
527 xpev = &e->xproperty;
528 if (xpev->state == PropertyNewValue &&
529 (xpev->atom == XA_PRIMARY ||
530 xpev->atom == clipboard)) {
538 ulong nitems, ofs, rem;
540 uchar *data, *last, *repl;
541 Atom type, incratom, property = None;
543 incratom = XInternAtom(xw.dpy, "INCR", 0);
546 if (e->type == SelectionNotify)
547 property = e->xselection.property;
548 else if (e->type == PropertyNotify)
549 property = e->xproperty.atom;
551 if (property == None)
555 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
556 BUFSIZ/4, False, AnyPropertyType,
557 &type, &format, &nitems, &rem,
559 fprintf(stderr, "Clipboard allocation failed\n");
563 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
565 * If there is some PropertyNotify with no data, then
566 * this is the signal of the selection owner that all
567 * data has been transferred. We won't need to receive
568 * PropertyNotify events anymore.
570 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
571 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
575 if (type == incratom) {
577 * Activate the PropertyNotify events so we receive
578 * when the selection owner does send us the next
581 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
582 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
586 * Deleting the property is the transfer start signal.
588 XDeleteProperty(xw.dpy, xw.win, (int)property);
594 * Line endings are inconsistent in the terminal and GUI world
595 * copy and pasting. When receiving some selection data,
596 * replace all '\n' with '\r'.
597 * FIXME: Fix the computer world.
600 last = data + nitems * format / 8;
601 while ((repl = memchr(repl, '\n', last - repl))) {
605 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
606 ttywrite("\033[200~", 6, 0);
607 ttywrite((char *)data, nitems * format / 8, 1);
608 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
609 ttywrite("\033[201~", 6, 0);
611 /* number of 32-bit chunks returned */
612 ofs += nitems * format / 32;
616 * Deleting the property again tells the selection owner to send the
617 * next data chunk in the property.
619 XDeleteProperty(xw.dpy, xw.win, (int)property);
635 selrequest(XEvent *e)
637 XSelectionRequestEvent *xsre;
639 Atom xa_targets, string, clipboard;
642 xsre = (XSelectionRequestEvent *) e;
643 xev.type = SelectionNotify;
644 xev.requestor = xsre->requestor;
645 xev.selection = xsre->selection;
646 xev.target = xsre->target;
647 xev.time = xsre->time;
648 if (xsre->property == None)
649 xsre->property = xsre->target;
654 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
655 if (xsre->target == xa_targets) {
656 /* respond with the supported type */
657 string = xsel.xtarget;
658 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
659 XA_ATOM, 32, PropModeReplace,
660 (uchar *) &string, 1);
661 xev.property = xsre->property;
662 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
664 * xith XA_STRING non ascii characters may be incorrect in the
665 * requestor. It is not our problem, use utf8.
667 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
668 if (xsre->selection == XA_PRIMARY) {
669 seltext = xsel.primary;
670 } else if (xsre->selection == clipboard) {
671 seltext = xsel.clipboard;
674 "Unhandled clipboard selection 0x%lx\n",
678 if (seltext != NULL) {
679 XChangeProperty(xsre->display, xsre->requestor,
680 xsre->property, xsre->target,
682 (uchar *)seltext, strlen(seltext));
683 xev.property = xsre->property;
687 /* all done, send a notification to the listener */
688 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
689 fprintf(stderr, "Error sending SelectionNotify event\n");
693 setsel(char *str, Time t)
701 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
702 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
709 setsel(str, CurrentTime);
715 for(plumbsel = 0; plumb_cmd[plumbsel]; plumbsel++);
724 if (subprocwd(cwd) != 0)
727 plumb_cmd[plumbsel] = sel;
729 switch(child = fork()) {
735 if (execvp(plumb_cmd[0], plumb_cmd) == -1)
739 waitpid(child, NULL, 0);
746 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
751 if (mouseaction(e, 1))
753 if (e->xbutton.button == Button1)
760 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
769 cresize(int width, int height)
778 col = (win.w - 2 * borderpx) / win.cw;
779 row = (win.h - 2 * borderpx) / win.ch;
785 ttyresize(win.tw, win.th);
789 xresize(int col, int row)
791 win.tw = col * win.cw;
792 win.th = row * win.ch;
794 XFreePixmap(xw.dpy, xw.buf);
795 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
796 DefaultDepth(xw.dpy, xw.scr));
797 XftDrawChange(xw.draw, xw.buf);
798 xclear(0, 0, win.w, win.h);
800 /* resize to new width */
801 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
807 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
811 xloadcolor(int i, const char *name, Color *ncolor)
813 XRenderColor color = { .alpha = 0xffff };
816 if (BETWEEN(i, 16, 255)) { /* 256 color */
817 if (i < 6*6*6+16) { /* same colors as xterm */
818 color.red = sixd_to_16bit( ((i-16)/36)%6 );
819 color.green = sixd_to_16bit( ((i-16)/6) %6 );
820 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
821 } else { /* greyscale */
822 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
823 color.green = color.blue = color.red;
825 return XftColorAllocValue(xw.dpy, xw.vis,
826 xw.cmap, &color, ncolor);
831 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
834 void normalMode() { historyModeToggle((win.mode ^=MODE_NORMAL) & MODE_NORMAL); }
844 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
845 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
847 dc.collen = MAX(LEN(colorname), 256);
848 dc.col = xmalloc(dc.collen * sizeof(Color));
851 for (i = 0; i < dc.collen; i++)
852 if (!xloadcolor(i, NULL, &dc.col[i])) {
854 die("could not allocate color '%s'\n", colorname[i]);
856 die("could not allocate color %d\n", i);
862 xsetcolorname(int x, const char *name)
866 if (!BETWEEN(x, 0, dc.collen))
869 if (!xloadcolor(x, name, &ncolor))
872 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
879 * Absolute coordinates.
882 xclear(int x1, int y1, int x2, int y2)
885 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
886 x1, y1, x2-x1, y2-y1);
892 XClassHint class = {opt_name ? opt_name : "st",
893 opt_class ? opt_class : "St"};
894 XWMHints wm = {.flags = InputHint, .input = 1};
897 sizeh = XAllocSizeHints();
899 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
900 sizeh->height = win.h;
901 sizeh->width = win.w;
902 sizeh->height_inc = win.ch;
903 sizeh->width_inc = win.cw;
904 sizeh->base_height = 2 * borderpx;
905 sizeh->base_width = 2 * borderpx;
906 sizeh->min_height = win.ch + 2 * borderpx;
907 sizeh->min_width = win.cw + 2 * borderpx;
909 sizeh->flags |= PMaxSize;
910 sizeh->min_width = sizeh->max_width = win.w;
911 sizeh->min_height = sizeh->max_height = win.h;
913 if (xw.gm & (XValue|YValue)) {
914 sizeh->flags |= USPosition | PWinGravity;
917 sizeh->win_gravity = xgeommasktogravity(xw.gm);
920 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
926 xgeommasktogravity(int mask)
928 switch (mask & (XNegative|YNegative)) {
930 return NorthWestGravity;
932 return NorthEastGravity;
934 return SouthWestGravity;
937 return SouthEastGravity;
941 xloadfont(Font *f, FcPattern *pattern)
943 FcPattern *configured;
947 int wantattr, haveattr;
950 * Manually configure instead of calling XftMatchFont
951 * so that we can use the configured pattern for
952 * "missing glyph" lookups.
954 configured = FcPatternDuplicate(pattern);
958 FcConfigSubstitute(NULL, configured, FcMatchPattern);
959 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
961 match = FcFontMatch(NULL, configured, &result);
963 FcPatternDestroy(configured);
967 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
968 FcPatternDestroy(configured);
969 FcPatternDestroy(match);
973 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
976 * Check if xft was unable to find a font with the appropriate
977 * slant but gave us one anyway. Try to mitigate.
979 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
980 &haveattr) != XftResultMatch) || haveattr < wantattr) {
982 fputs("font slant does not match\n", stderr);
986 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
988 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
989 &haveattr) != XftResultMatch) || haveattr != wantattr) {
991 fputs("font weight does not match\n", stderr);
995 XftTextExtentsUtf8(xw.dpy, f->match,
996 (const FcChar8 *) ascii_printable,
997 strlen(ascii_printable), &extents);
1000 f->pattern = configured;
1002 f->ascent = f->match->ascent;
1003 f->descent = f->match->descent;
1005 f->rbearing = f->match->max_advance_width;
1007 f->height = f->ascent + f->descent;
1008 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
1014 xloadfonts(char *fontstr, double fontsize)
1019 if (fontstr[0] == '-')
1020 pattern = XftXlfdParse(fontstr, False, False);
1022 pattern = FcNameParse((FcChar8 *)fontstr);
1025 die("can't open font %s\n", fontstr);
1028 FcPatternDel(pattern, FC_PIXEL_SIZE);
1029 FcPatternDel(pattern, FC_SIZE);
1030 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
1031 usedfontsize = fontsize;
1033 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
1035 usedfontsize = fontval;
1036 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
1041 * Default font size is 12, if none given. This is to
1042 * have a known usedfontsize value.
1044 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1047 defaultfontsize = usedfontsize;
1050 if (xloadfont(&dc.font, pattern))
1051 die("can't open font %s\n", fontstr);
1053 if (usedfontsize < 0) {
1054 FcPatternGetDouble(dc.font.match->pattern,
1055 FC_PIXEL_SIZE, 0, &fontval);
1056 usedfontsize = fontval;
1058 defaultfontsize = fontval;
1061 /* Setting character width and height. */
1062 win.cw = ceilf(dc.font.width * cwscale);
1063 win.ch = ceilf(dc.font.height * chscale);
1065 FcPatternDel(pattern, FC_SLANT);
1066 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1067 if (xloadfont(&dc.ifont, pattern))
1068 die("can't open font %s\n", fontstr);
1070 FcPatternDel(pattern, FC_WEIGHT);
1071 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1072 if (xloadfont(&dc.ibfont, pattern))
1073 die("can't open font %s\n", fontstr);
1075 FcPatternDel(pattern, FC_SLANT);
1076 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1077 if (xloadfont(&dc.bfont, pattern))
1078 die("can't open font %s\n", fontstr);
1080 FcPatternDestroy(pattern);
1084 xunloadfont(Font *f)
1086 XftFontClose(xw.dpy, f->match);
1087 FcPatternDestroy(f->pattern);
1089 FcFontSetDestroy(f->set);
1095 /* Free the loaded fonts in the font cache. */
1097 XftFontClose(xw.dpy, frc[--frclen].font);
1099 xunloadfont(&dc.font);
1100 xunloadfont(&dc.bfont);
1101 xunloadfont(&dc.ifont);
1102 xunloadfont(&dc.ibfont);
1106 ximopen(Display *dpy)
1108 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1109 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1111 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1112 if (xw.ime.xim == NULL)
1115 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1116 fprintf(stderr, "XSetIMValues: "
1117 "Could not set XNDestroyCallback.\n");
1119 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1122 if (xw.ime.xic == NULL) {
1123 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1124 XIMPreeditNothing | XIMStatusNothing,
1125 XNClientWindow, xw.win,
1126 XNDestroyCallback, &icdestroy,
1129 if (xw.ime.xic == NULL)
1130 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1136 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1139 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1140 ximinstantiate, NULL);
1144 ximdestroy(XIM xim, XPointer client, XPointer call)
1147 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1148 ximinstantiate, NULL);
1149 XFree(xw.ime.spotlist);
1153 xicdestroy(XIC xim, XPointer client, XPointer call)
1160 xinit(int cols, int rows)
1165 pid_t thispid = getpid();
1166 XColor xmousefg, xmousebg;
1168 xw.scr = XDefaultScreen(xw.dpy);
1169 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1173 die("could not init fontconfig.\n");
1175 usedfont = (opt_font == NULL)? font : opt_font;
1176 xloadfonts(usedfont, 0);
1179 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1182 /* adjust fixed window geometry */
1183 win.w = 2 * borderpx + cols * win.cw;
1184 win.h = 2 * borderpx + rows * win.ch;
1185 if (xw.gm & XNegative)
1186 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1187 if (xw.gm & YNegative)
1188 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1191 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1192 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1193 xw.attrs.bit_gravity = NorthWestGravity;
1194 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1195 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1196 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1197 xw.attrs.colormap = xw.cmap;
1199 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1200 parent = XRootWindow(xw.dpy, xw.scr);
1201 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1202 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1203 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1204 | CWEventMask | CWColormap, &xw.attrs);
1206 memset(&gcvalues, 0, sizeof(gcvalues));
1207 gcvalues.graphics_exposures = False;
1208 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1210 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1211 DefaultDepth(xw.dpy, xw.scr));
1212 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1213 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1215 /* font spec buffer */
1216 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1218 /* Xft rendering context */
1219 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1222 if (!ximopen(xw.dpy)) {
1223 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1224 ximinstantiate, NULL);
1227 /* white cursor, black outline */
1228 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1229 XDefineCursor(xw.dpy, xw.win, cursor);
1231 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1232 xmousefg.red = 0xffff;
1233 xmousefg.green = 0xffff;
1234 xmousefg.blue = 0xffff;
1237 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1238 xmousebg.red = 0x0000;
1239 xmousebg.green = 0x0000;
1240 xmousebg.blue = 0x0000;
1243 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1245 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1246 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1247 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1248 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1250 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1251 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1252 PropModeReplace, (uchar *)&thispid, 1);
1254 win.mode = MODE_NUMLOCK;
1257 XMapWindow(xw.dpy, xw.win);
1258 XSync(xw.dpy, False);
1260 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1261 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1262 xsel.primary = NULL;
1263 xsel.clipboard = NULL;
1264 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1265 if (xsel.xtarget == None)
1266 xsel.xtarget = XA_STRING;
1270 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1272 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1273 ushort mode, prevmode = USHRT_MAX;
1274 Font *font = &dc.font;
1275 int frcflags = FRC_NORMAL;
1276 float runewidth = win.cw;
1280 FcPattern *fcpattern, *fontpattern;
1281 FcFontSet *fcsets[] = { NULL };
1282 FcCharSet *fccharset;
1283 int i, f, numspecs = 0;
1285 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1286 /* Fetch rune and mode for current glyph. */
1287 Glyph g = glyphs[i];
1288 historyOverlay(x+i, y, &g);
1292 /* Skip dummy wide-character spacing. */
1293 if (mode == ATTR_WDUMMY)
1296 /* Determine font for glyph if different from previous glyph. */
1297 if (prevmode != mode) {
1300 frcflags = FRC_NORMAL;
1301 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1302 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1304 frcflags = FRC_ITALICBOLD;
1305 } else if (mode & ATTR_ITALIC) {
1307 frcflags = FRC_ITALIC;
1308 } else if (mode & ATTR_BOLD) {
1310 frcflags = FRC_BOLD;
1312 yp = winy + font->ascent;
1315 /* Lookup character index with default font. */
1316 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1318 specs[numspecs].font = font->match;
1319 specs[numspecs].glyph = glyphidx;
1320 specs[numspecs].x = (short)xp;
1321 specs[numspecs].y = (short)yp;
1327 /* Fallback on font cache, search the font cache for match. */
1328 for (f = 0; f < frclen; f++) {
1329 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1330 /* Everything correct. */
1331 if (glyphidx && frc[f].flags == frcflags)
1333 /* We got a default font for a not found glyph. */
1334 if (!glyphidx && frc[f].flags == frcflags
1335 && frc[f].unicodep == rune) {
1340 /* Nothing was found. Use fontconfig to find matching font. */
1343 font->set = FcFontSort(0, font->pattern,
1345 fcsets[0] = font->set;
1348 * Nothing was found in the cache. Now use
1349 * some dozen of Fontconfig calls to get the
1350 * font for one single character.
1352 * Xft and fontconfig are design failures.
1354 fcpattern = FcPatternDuplicate(font->pattern);
1355 fccharset = FcCharSetCreate();
1357 FcCharSetAddChar(fccharset, rune);
1358 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1360 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1362 FcConfigSubstitute(0, fcpattern,
1364 FcDefaultSubstitute(fcpattern);
1366 fontpattern = FcFontSetMatch(0, fcsets, 1,
1369 /* Allocate memory for the new cache entry. */
1370 if (frclen >= frccap) {
1372 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1375 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1377 if (!frc[frclen].font)
1378 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1380 frc[frclen].flags = frcflags;
1381 frc[frclen].unicodep = rune;
1383 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1388 FcPatternDestroy(fcpattern);
1389 FcCharSetDestroy(fccharset);
1392 specs[numspecs].font = frc[f].font;
1393 specs[numspecs].glyph = glyphidx;
1394 specs[numspecs].x = (short)xp;
1395 specs[numspecs].y = (short)yp;
1404 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1406 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1407 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1408 width = charlen * win.cw;
1409 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1410 XRenderColor colfg, colbg;
1413 /* Fallback on color display for attributes not supported by the font */
1414 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1415 if (dc.ibfont.badslant || dc.ibfont.badweight)
1416 base.fg = defaultattr;
1417 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1418 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1419 base.fg = defaultattr;
1422 if (IS_TRUECOL(base.fg)) {
1423 colfg.alpha = 0xffff;
1424 colfg.red = TRUERED(base.fg);
1425 colfg.green = TRUEGREEN(base.fg);
1426 colfg.blue = TRUEBLUE(base.fg);
1427 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1430 fg = &dc.col[base.fg];
1433 if (IS_TRUECOL(base.bg)) {
1434 colbg.alpha = 0xffff;
1435 colbg.green = TRUEGREEN(base.bg);
1436 colbg.red = TRUERED(base.bg);
1437 colbg.blue = TRUEBLUE(base.bg);
1438 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1441 bg = &dc.col[base.bg];
1444 /* Change basic system colors [0-7] to bright system colors [8-15] */
1445 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1446 fg = &dc.col[base.fg + 8];
1448 if (IS_SET(MODE_REVERSE)) {
1449 if (fg == &dc.col[defaultfg]) {
1450 fg = &dc.col[defaultbg];
1452 colfg.red = ~fg->color.red;
1453 colfg.green = ~fg->color.green;
1454 colfg.blue = ~fg->color.blue;
1455 colfg.alpha = fg->color.alpha;
1456 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1461 if (bg == &dc.col[defaultbg]) {
1462 bg = &dc.col[defaultfg];
1464 colbg.red = ~bg->color.red;
1465 colbg.green = ~bg->color.green;
1466 colbg.blue = ~bg->color.blue;
1467 colbg.alpha = bg->color.alpha;
1468 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1474 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1475 colfg.red = fg->color.red / 2;
1476 colfg.green = fg->color.green / 2;
1477 colfg.blue = fg->color.blue / 2;
1478 colfg.alpha = fg->color.alpha;
1479 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1483 if (base.mode & ATTR_REVERSE) {
1489 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1492 if (base.mode & ATTR_INVISIBLE)
1495 /* Intelligent cleaning up of the borders. */
1497 xclear(0, (y == 0)? 0 : winy, borderpx,
1499 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1501 if (winx + width >= borderpx + win.tw) {
1502 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1503 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1506 xclear(winx, 0, winx + width, borderpx);
1507 if (winy + win.ch >= borderpx + win.th)
1508 xclear(winx, winy + win.ch, winx + width, win.h);
1510 /* Clean up the region we want to draw to. */
1511 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1513 /* Set the clip region because Xft is sometimes dirty. */
1518 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1520 /* Render the glyphs. */
1521 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1523 /* Render underline and strikethrough. */
1524 if (base.mode & ATTR_UNDERLINE) {
1525 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1529 if (base.mode & ATTR_STRUCK) {
1530 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1534 /* Reset clip to none. */
1535 XftDrawSetClip(xw.draw, 0);
1539 xdrawglyph(Glyph g, int x, int y)
1542 XftGlyphFontSpec spec;
1544 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1545 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1549 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1553 /* remove the old cursor */
1554 if (selected(ox, oy))
1555 og.mode ^= ATTR_REVERSE;
1556 xdrawglyph(og, ox, oy);
1558 if (IS_SET(MODE_HIDE))
1562 * Select the right color for the right mode.
1564 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1566 if (IS_SET(MODE_REVERSE)) {
1567 g.mode |= ATTR_REVERSE;
1569 if (selected(cx, cy)) {
1570 drawcol = dc.col[defaultcs];
1573 drawcol = dc.col[defaultrcs];
1577 if (selected(cx, cy)) {
1584 drawcol = dc.col[g.bg];
1587 /* draw the new one */
1588 if (IS_SET(MODE_FOCUSED)) {
1589 switch (win.cursor) {
1590 case 0: /* Blinking block */
1591 case 1: /* Blinking block (default) */
1592 if (IS_SET(MODE_BLINK))
1595 case 2: /* Steady block */
1596 xdrawglyph(g, cx, cy);
1598 case 3: /* Blinking underline */
1599 if (IS_SET(MODE_BLINK))
1602 case 4: /* Steady underline */
1603 XftDrawRect(xw.draw, &drawcol,
1604 borderpx + cx * win.cw,
1605 borderpx + (cy + 1) * win.ch - \
1607 win.cw, cursorthickness);
1609 case 5: /* Blinking bar */
1610 if (IS_SET(MODE_BLINK))
1613 case 6: /* Steady bar */
1614 XftDrawRect(xw.draw, &drawcol,
1615 borderpx + cx * win.cw,
1616 borderpx + cy * win.ch,
1617 cursorthickness, win.ch);
1619 case 7: /* Blinking st cursor */
1620 if (IS_SET(MODE_BLINK))
1623 case 8: /* Steady st cursor */
1625 xdrawglyph(g, cx, cy);
1629 XftDrawRect(xw.draw, &drawcol,
1630 borderpx + cx * win.cw,
1631 borderpx + cy * win.ch,
1633 XftDrawRect(xw.draw, &drawcol,
1634 borderpx + cx * win.cw,
1635 borderpx + cy * win.ch,
1637 XftDrawRect(xw.draw, &drawcol,
1638 borderpx + (cx + 1) * win.cw - 1,
1639 borderpx + cy * win.ch,
1641 XftDrawRect(xw.draw, &drawcol,
1642 borderpx + cx * win.cw,
1643 borderpx + (cy + 1) * win.ch - 1,
1651 char buf[sizeof(long) * 8 + 1];
1653 snprintf(buf, sizeof(buf), "%lu", xw.win);
1654 setenv("WINDOWID", buf, 1);
1661 DEFAULT(p, opt_title);
1663 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1665 XSetWMName(xw.dpy, xw.win, &prop);
1666 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1673 if (IS_SET(MODE_VISIBLE))
1674 XCopyArea(xw.dpy, xw.win, xw.buf, dc.gc, 0, 0, win.w, win.h, 0, 0);
1675 return IS_SET(MODE_VISIBLE);
1679 xdrawline(Line line, int x1, int y1, int x2)
1681 int i, x, ox, numspecs;
1683 XftGlyphFontSpec *specs = xw.specbuf;
1685 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1687 for (x = x1; x < x2 && i < numspecs; x++) {
1689 historyOverlay(x, y1, &new);
1690 if (new.mode == ATTR_WDUMMY)
1692 if (selected(x, y1))
1693 new.mode ^= ATTR_REVERSE;
1694 if (i > 0 && ATTRCMP(base, new)) {
1695 xdrawglyphfontspecs(specs, base, i, ox, y1);
1707 xdrawglyphfontspecs(specs, base, i, ox, y1);
1713 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1715 XSetForeground(xw.dpy, dc.gc,
1716 dc.col[IS_SET(MODE_REVERSE)?
1717 defaultfg : defaultbg].pixel);
1721 xximspot(int x, int y)
1723 if (xw.ime.xic == NULL)
1726 xw.ime.spot.x = borderpx + x * win.cw;
1727 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1729 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1739 visibility(XEvent *ev)
1741 XVisibilityEvent *e = &ev->xvisibility;
1743 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1749 win.mode &= ~MODE_VISIBLE;
1753 xsetpointermotion(int set)
1755 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1756 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1760 xsetmode(int set, unsigned int flags)
1762 int mode = win.mode;
1763 MODBIT(win.mode, set, flags);
1764 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1769 xsetcursor(int cursor)
1771 if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1773 win.cursor = cursor;
1774 cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1775 win.cursor == 3 || win.cursor == 5 ||
1781 xseturgency(int add)
1783 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1785 MODBIT(h->flags, add, XUrgencyHint);
1786 XSetWMHints(xw.dpy, xw.win, h);
1793 if (!(IS_SET(MODE_FOCUSED)))
1796 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1802 XFocusChangeEvent *e = &ev->xfocus;
1804 if (e->mode == NotifyGrab)
1807 if (ev->type == FocusIn) {
1809 XSetICFocus(xw.ime.xic);
1810 win.mode |= MODE_FOCUSED;
1812 if (IS_SET(MODE_FOCUS))
1813 ttywrite("\033[I", 3, 0);
1816 XUnsetICFocus(xw.ime.xic);
1817 win.mode &= ~MODE_FOCUSED;
1818 if (IS_SET(MODE_FOCUS))
1819 ttywrite("\033[O", 3, 0);
1824 match(uint mask, uint state)
1826 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1830 kmap(KeySym k, uint state)
1835 /* Check for mapped keys out of X11 function keys. */
1836 for (i = 0; i < LEN(mappedkeys); i++) {
1837 if (mappedkeys[i] == k)
1840 if (i == LEN(mappedkeys)) {
1841 if ((k & 0xFFFF) < 0xFD00)
1845 for (kp = key; kp < key + LEN(key); kp++) {
1849 if (!match(kp->mask, state))
1852 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1854 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1857 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1869 XKeyEvent *e = &ev->xkey;
1871 char buf[64], *customkey;
1877 if (IS_SET(MODE_KBDLOCK))
1881 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1883 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1884 if (IS_SET(MODE_NORMAL)) {
1885 if (kpressHist(buf, len, match(ControlMask, e->state), &ksym)
1886 == finished) normalMode();
1890 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1891 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1892 bp->func(&(bp->arg));
1897 /* 2. custom keys from config.h */
1898 if ((customkey = kmap(ksym, e->state))) {
1899 ttywrite(customkey, strlen(customkey), 1);
1903 /* 3. composed string from input method */
1906 if (len == 1 && e->state & Mod1Mask) {
1907 if (IS_SET(MODE_8BIT)) {
1910 len = utf8encode(c, buf);
1918 ttywrite(buf, len, 1);
1926 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1928 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1929 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1930 win.mode |= MODE_FOCUSED;
1932 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1933 win.mode &= ~MODE_FOCUSED;
1935 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1944 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1947 cresize(e->xconfigure.width, e->xconfigure.height);
1954 int w = win.w, h = win.h;
1956 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1957 struct timespec seltv, *tv, now, lastblink, trigger;
1960 /* Waiting for window mapping */
1962 XNextEvent(xw.dpy, &ev);
1964 * This XFilterEvent call is required because of XOpenIM. It
1965 * does filter out the key event and some client message for
1966 * the input method too.
1968 if (XFilterEvent(&ev, None))
1970 if (ev.type == ConfigureNotify) {
1971 w = ev.xconfigure.width;
1972 h = ev.xconfigure.height;
1974 } while (ev.type != MapNotify);
1976 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1979 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1981 FD_SET(ttyfd, &rfd);
1984 if (XPending(xw.dpy))
1985 timeout = 0; /* existing events might not set xfd */
1987 seltv.tv_sec = timeout / 1E3;
1988 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1989 tv = timeout >= 0 ? &seltv : NULL;
1991 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1994 die("select failed: %s\n", strerror(errno));
1996 clock_gettime(CLOCK_MONOTONIC, &now);
1998 if (FD_ISSET(ttyfd, &rfd))
2002 while (XPending(xw.dpy)) {
2004 XNextEvent(xw.dpy, &ev);
2005 if (XFilterEvent(&ev, None))
2007 if (handler[ev.type])
2008 (handler[ev.type])(&ev);
2012 * To reduce flicker and tearing, when new content or event
2013 * triggers drawing, we first wait a bit to ensure we got
2014 * everything, and if nothing new arrives - we draw.
2015 * We start with trying to wait minlatency ms. If more content
2016 * arrives sooner, we retry with shorter and shorter periods,
2017 * and eventually draw even without idle after maxlatency ms.
2018 * Typically this results in low latency while interacting,
2019 * maximum latency intervals during `cat huge.txt`, and perfect
2020 * sync with periodic updates from animations/key-repeats/etc.
2022 if (FD_ISSET(ttyfd, &rfd) || xev) {
2025 if (IS_SET(MODE_BLINK)) {
2026 win.mode ^= MODE_BLINK;
2031 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
2032 / maxlatency * minlatency;
2034 continue; /* we have time, try to find idle */
2037 /* idle detected or maxlatency exhausted -> draw */
2039 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
2040 timeout = blinktimeout - TIMEDIFF(now, lastblink);
2042 if (-timeout > blinktimeout) /* start visible */
2043 win.mode |= MODE_BLINK;
2044 win.mode ^= MODE_BLINK;
2045 tsetdirtattr(ATTR_BLINK);
2047 timeout = blinktimeout;
2058 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2065 char fullclass[256];
2069 snprintf(fullname, sizeof(fullname), "%s.%s",
2070 opt_name ? opt_name : "st", name);
2071 snprintf(fullclass, sizeof(fullclass), "%s.%s",
2072 opt_class ? opt_class : "St", name);
2073 fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
2075 XrmGetResource(db, fullname, fullclass, &type, &ret);
2076 if (ret.addr == NULL || strncmp("String", type, 64))
2084 *idst = strtoul(ret.addr, NULL, 10);
2087 *fdst = strtof(ret.addr, NULL);
2101 resm = XResourceManagerString(xw.dpy);
2105 db = XrmGetStringDatabase(resm);
2106 for (p = resources; p < resources + LEN(resources); p++)
2107 resource_load(db, p->name, p->type, p->dst);
2113 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2114 " [-n name] [-o file]\n"
2115 " [-T title] [-t title] [-w windowid]"
2116 " [[-e] command [args ...]]\n"
2117 " %s [-aiv] [-c class] [-f font] [-g geometry]"
2118 " [-n name] [-o file]\n"
2119 " [-T title] [-t title] [-w windowid] -l line"
2120 " [stty_args ...]\n", argv0, argv0);
2124 main(int argc, char *argv[])
2128 xsetcursor(cursorstyle);
2135 opt_class = EARGF(usage());
2142 opt_font = EARGF(usage());
2145 xw.gm = XParseGeometry(EARGF(usage()),
2146 &xw.l, &xw.t, &cols, &rows);
2152 opt_io = EARGF(usage());
2155 opt_line = EARGF(usage());
2158 opt_name = EARGF(usage());
2162 opt_title = EARGF(usage());
2165 opt_embed = EARGF(usage());
2168 die("%s " VERSION "\n", argv0);
2176 if (argc > 0) /* eat all remaining arguments */
2180 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2182 setlocale(LC_CTYPE, "");
2183 XSetLocaleModifiers("");
2185 if(!(xw.dpy = XOpenDisplay(NULL)))
2186 die("Can't open display\n");
2189 cols = MAX(cols, 1);
2190 rows = MAX(rows, 1);