fix possible rare crash when Xutf8TextPropertyToTextList fails
[st.git] / x.c
blob89786b8bd7a5db38ab008c2d7287b49e86e01d60
1 /* See LICENSE for license details. */
2 #include <errno.h>
3 #include <math.h>
4 #include <limits.h>
5 #include <locale.h>
6 #include <signal.h>
7 #include <sys/select.h>
8 #include <time.h>
9 #include <unistd.h>
10 #include <libgen.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xlib.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
18 char *argv0;
19 #include "arg.h"
20 #include "st.h"
21 #include "win.h"
23 /* types used in config.h */
24 typedef struct {
25 uint mod;
26 KeySym keysym;
27 void (*func)(const Arg *);
28 const Arg arg;
29 } Shortcut;
31 typedef struct {
32 uint mod;
33 uint button;
34 void (*func)(const Arg *);
35 const Arg arg;
36 uint release;
37 } MouseShortcut;
39 typedef struct {
40 KeySym k;
41 uint mask;
42 char *s;
43 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
44 signed char appkey; /* application keypad */
45 signed char appcursor; /* application cursor */
46 } Key;
48 /* X modifiers */
49 #define XK_ANY_MOD UINT_MAX
50 #define XK_NO_MOD 0
51 #define XK_SWITCH_MOD (1<<13|1<<14)
53 /* function definitions used in config.h */
54 static void clipcopy(const Arg *);
55 static void clippaste(const Arg *);
56 static void numlock(const Arg *);
57 static void selpaste(const Arg *);
58 static void zoom(const Arg *);
59 static void zoomabs(const Arg *);
60 static void zoomreset(const Arg *);
61 static void ttysend(const Arg *);
63 /* config.h for applying patches and the configuration. */
64 #include "config.h"
66 /* XEMBED messages */
67 #define XEMBED_FOCUS_IN 4
68 #define XEMBED_FOCUS_OUT 5
70 /* macros */
71 #define IS_SET(flag) ((win.mode & (flag)) != 0)
72 #define TRUERED(x) (((x) & 0xff0000) >> 8)
73 #define TRUEGREEN(x) (((x) & 0xff00))
74 #define TRUEBLUE(x) (((x) & 0xff) << 8)
76 typedef XftDraw *Draw;
77 typedef XftColor Color;
78 typedef XftGlyphFontSpec GlyphFontSpec;
80 /* Purely graphic info */
81 typedef struct {
82 int tw, th; /* tty width and height */
83 int w, h; /* window width and height */
84 int ch; /* char height */
85 int cw; /* char width */
86 int mode; /* window state/mode flags */
87 int cursor; /* cursor style */
88 } TermWindow;
90 typedef struct {
91 Display *dpy;
92 Colormap cmap;
93 Window win;
94 Drawable buf;
95 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
96 Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
97 struct {
98 XIM xim;
99 XIC xic;
100 XPoint spot;
101 XVaNestedList spotlist;
102 } ime;
103 Draw draw;
104 Visual *vis;
105 XSetWindowAttributes attrs;
106 int scr;
107 int isfixed; /* is fixed geometry? */
108 int l, t; /* left and top offset */
109 int gm; /* geometry mask */
110 } XWindow;
112 typedef struct {
113 Atom xtarget;
114 char *primary, *clipboard;
115 struct timespec tclick1;
116 struct timespec tclick2;
117 } XSelection;
119 /* Font structure */
120 #define Font Font_
121 typedef struct {
122 int height;
123 int width;
124 int ascent;
125 int descent;
126 int badslant;
127 int badweight;
128 short lbearing;
129 short rbearing;
130 XftFont *match;
131 FcFontSet *set;
132 FcPattern *pattern;
133 } Font;
135 /* Drawing Context */
136 typedef struct {
137 Color *col;
138 size_t collen;
139 Font font, bfont, ifont, ibfont;
140 GC gc;
141 } DC;
143 static inline ushort sixd_to_16bit(int);
144 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
145 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
146 static void xdrawglyph(Glyph, int, int);
147 static void xclear(int, int, int, int);
148 static int xgeommasktogravity(int);
149 static int ximopen(Display *);
150 static void ximinstantiate(Display *, XPointer, XPointer);
151 static void ximdestroy(XIM, XPointer, XPointer);
152 static int xicdestroy(XIC, XPointer, XPointer);
153 static void xinit(int, int);
154 static void cresize(int, int);
155 static void xresize(int, int);
156 static void xhints(void);
157 static int xloadcolor(int, const char *, Color *);
158 static int xloadfont(Font *, FcPattern *);
159 static void xloadfonts(const char *, double);
160 static void xunloadfont(Font *);
161 static void xunloadfonts(void);
162 static void xsetenv(void);
163 static void xseturgency(int);
164 static int evcol(XEvent *);
165 static int evrow(XEvent *);
167 static void expose(XEvent *);
168 static void visibility(XEvent *);
169 static void unmap(XEvent *);
170 static void kpress(XEvent *);
171 static void cmessage(XEvent *);
172 static void resize(XEvent *);
173 static void focus(XEvent *);
174 static uint buttonmask(uint);
175 static int mouseaction(XEvent *, uint);
176 static void brelease(XEvent *);
177 static void bpress(XEvent *);
178 static void bmotion(XEvent *);
179 static void propnotify(XEvent *);
180 static void selnotify(XEvent *);
181 static void selclear_(XEvent *);
182 static void selrequest(XEvent *);
183 static void setsel(char *, Time);
184 static void mousesel(XEvent *, int);
185 static void mousereport(XEvent *);
186 static char *kmap(KeySym, uint);
187 static int match(uint, uint);
189 static void run(void);
190 static void usage(void);
192 static void (*handler[LASTEvent])(XEvent *) = {
193 [KeyPress] = kpress,
194 [ClientMessage] = cmessage,
195 [ConfigureNotify] = resize,
196 [VisibilityNotify] = visibility,
197 [UnmapNotify] = unmap,
198 [Expose] = expose,
199 [FocusIn] = focus,
200 [FocusOut] = focus,
201 [MotionNotify] = bmotion,
202 [ButtonPress] = bpress,
203 [ButtonRelease] = brelease,
205 * Uncomment if you want the selection to disappear when you select something
206 * different in another window.
208 /* [SelectionClear] = selclear_, */
209 [SelectionNotify] = selnotify,
211 * PropertyNotify is only turned on when there is some INCR transfer happening
212 * for the selection retrieval.
214 [PropertyNotify] = propnotify,
215 [SelectionRequest] = selrequest,
218 /* Globals */
219 static DC dc;
220 static XWindow xw;
221 static XSelection xsel;
222 static TermWindow win;
224 /* Font Ring Cache */
225 enum {
226 FRC_NORMAL,
227 FRC_ITALIC,
228 FRC_BOLD,
229 FRC_ITALICBOLD
232 typedef struct {
233 XftFont *font;
234 int flags;
235 Rune unicodep;
236 } Fontcache;
238 /* Fontcache is an array now. A new font will be appended to the array. */
239 static Fontcache *frc = NULL;
240 static int frclen = 0;
241 static int frccap = 0;
242 static char *usedfont = NULL;
243 static double usedfontsize = 0;
244 static double defaultfontsize = 0;
246 static char *opt_class = NULL;
247 static char **opt_cmd = NULL;
248 static char *opt_embed = NULL;
249 static char *opt_font = NULL;
250 static char *opt_io = NULL;
251 static char *opt_line = NULL;
252 static char *opt_name = NULL;
253 static char *opt_title = NULL;
255 static int oldbutton = 3; /* button event on startup: 3 = release */
257 void
258 clipcopy(const Arg *dummy)
260 Atom clipboard;
262 free(xsel.clipboard);
263 xsel.clipboard = NULL;
265 if (xsel.primary != NULL) {
266 xsel.clipboard = xstrdup(xsel.primary);
267 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
268 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
272 void
273 clippaste(const Arg *dummy)
275 Atom clipboard;
277 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
278 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
279 xw.win, CurrentTime);
282 void
283 selpaste(const Arg *dummy)
285 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
286 xw.win, CurrentTime);
289 void
290 numlock(const Arg *dummy)
292 win.mode ^= MODE_NUMLOCK;
295 void
296 zoom(const Arg *arg)
298 Arg larg;
300 larg.f = usedfontsize + arg->f;
301 zoomabs(&larg);
304 void
305 zoomabs(const Arg *arg)
307 xunloadfonts();
308 xloadfonts(usedfont, arg->f);
309 cresize(0, 0);
310 redraw();
311 xhints();
314 void
315 zoomreset(const Arg *arg)
317 Arg larg;
319 if (defaultfontsize > 0) {
320 larg.f = defaultfontsize;
321 zoomabs(&larg);
325 void
326 ttysend(const Arg *arg)
328 ttywrite(arg->s, strlen(arg->s), 1);
332 evcol(XEvent *e)
334 int x = e->xbutton.x - borderpx;
335 LIMIT(x, 0, win.tw - 1);
336 return x / win.cw;
340 evrow(XEvent *e)
342 int y = e->xbutton.y - borderpx;
343 LIMIT(y, 0, win.th - 1);
344 return y / win.ch;
347 void
348 mousesel(XEvent *e, int done)
350 int type, seltype = SEL_REGULAR;
351 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
353 for (type = 1; type < LEN(selmasks); ++type) {
354 if (match(selmasks[type], state)) {
355 seltype = type;
356 break;
359 selextend(evcol(e), evrow(e), seltype, done);
360 if (done)
361 setsel(getsel(), e->xbutton.time);
364 void
365 mousereport(XEvent *e)
367 int len, x = evcol(e), y = evrow(e),
368 button = e->xbutton.button, state = e->xbutton.state;
369 char buf[40];
370 static int ox, oy;
372 /* from urxvt */
373 if (e->xbutton.type == MotionNotify) {
374 if (x == ox && y == oy)
375 return;
376 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
377 return;
378 /* MOUSE_MOTION: no reporting if no button is pressed */
379 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
380 return;
382 button = oldbutton + 32;
383 ox = x;
384 oy = y;
385 } else {
386 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
387 button = 3;
388 } else {
389 button -= Button1;
390 if (button >= 7)
391 button += 128 - 7;
392 else if (button >= 3)
393 button += 64 - 3;
395 if (e->xbutton.type == ButtonPress) {
396 oldbutton = button;
397 ox = x;
398 oy = y;
399 } else if (e->xbutton.type == ButtonRelease) {
400 oldbutton = 3;
401 /* MODE_MOUSEX10: no button release reporting */
402 if (IS_SET(MODE_MOUSEX10))
403 return;
404 if (button == 64 || button == 65)
405 return;
409 if (!IS_SET(MODE_MOUSEX10)) {
410 button += ((state & ShiftMask ) ? 4 : 0)
411 + ((state & Mod4Mask ) ? 8 : 0)
412 + ((state & ControlMask) ? 16 : 0);
415 if (IS_SET(MODE_MOUSESGR)) {
416 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
417 button, x+1, y+1,
418 e->xbutton.type == ButtonRelease ? 'm' : 'M');
419 } else if (x < 223 && y < 223) {
420 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
421 32+button, 32+x+1, 32+y+1);
422 } else {
423 return;
426 ttywrite(buf, len, 0);
429 uint
430 buttonmask(uint button)
432 return button == Button1 ? Button1Mask
433 : button == Button2 ? Button2Mask
434 : button == Button3 ? Button3Mask
435 : button == Button4 ? Button4Mask
436 : button == Button5 ? Button5Mask
437 : 0;
441 mouseaction(XEvent *e, uint release)
443 MouseShortcut *ms;
445 /* ignore Button<N>mask for Button<N> - it's set on release */
446 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
448 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
449 if (ms->release == release &&
450 ms->button == e->xbutton.button &&
451 (match(ms->mod, state) || /* exact or forced */
452 match(ms->mod, state & ~forcemousemod))) {
453 ms->func(&(ms->arg));
454 return 1;
458 return 0;
461 void
462 bpress(XEvent *e)
464 struct timespec now;
465 int snap;
467 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
468 mousereport(e);
469 return;
472 if (mouseaction(e, 0))
473 return;
475 if (e->xbutton.button == Button1) {
477 * If the user clicks below predefined timeouts specific
478 * snapping behaviour is exposed.
480 clock_gettime(CLOCK_MONOTONIC, &now);
481 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
482 snap = SNAP_LINE;
483 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
484 snap = SNAP_WORD;
485 } else {
486 snap = 0;
488 xsel.tclick2 = xsel.tclick1;
489 xsel.tclick1 = now;
491 selstart(evcol(e), evrow(e), snap);
495 void
496 propnotify(XEvent *e)
498 XPropertyEvent *xpev;
499 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
501 xpev = &e->xproperty;
502 if (xpev->state == PropertyNewValue &&
503 (xpev->atom == XA_PRIMARY ||
504 xpev->atom == clipboard)) {
505 selnotify(e);
509 void
510 selnotify(XEvent *e)
512 ulong nitems, ofs, rem;
513 int format;
514 uchar *data, *last, *repl;
515 Atom type, incratom, property = None;
517 incratom = XInternAtom(xw.dpy, "INCR", 0);
519 ofs = 0;
520 if (e->type == SelectionNotify)
521 property = e->xselection.property;
522 else if (e->type == PropertyNotify)
523 property = e->xproperty.atom;
525 if (property == None)
526 return;
528 do {
529 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
530 BUFSIZ/4, False, AnyPropertyType,
531 &type, &format, &nitems, &rem,
532 &data)) {
533 fprintf(stderr, "Clipboard allocation failed\n");
534 return;
537 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
539 * If there is some PropertyNotify with no data, then
540 * this is the signal of the selection owner that all
541 * data has been transferred. We won't need to receive
542 * PropertyNotify events anymore.
544 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
545 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
546 &xw.attrs);
549 if (type == incratom) {
551 * Activate the PropertyNotify events so we receive
552 * when the selection owner does send us the next
553 * chunk of data.
555 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
556 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
557 &xw.attrs);
560 * Deleting the property is the transfer start signal.
562 XDeleteProperty(xw.dpy, xw.win, (int)property);
563 continue;
567 * As seen in getsel:
568 * Line endings are inconsistent in the terminal and GUI world
569 * copy and pasting. When receiving some selection data,
570 * replace all '\n' with '\r'.
571 * FIXME: Fix the computer world.
573 repl = data;
574 last = data + nitems * format / 8;
575 while ((repl = memchr(repl, '\n', last - repl))) {
576 *repl++ = '\r';
579 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
580 ttywrite("\033[200~", 6, 0);
581 ttywrite((char *)data, nitems * format / 8, 1);
582 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
583 ttywrite("\033[201~", 6, 0);
584 XFree(data);
585 /* number of 32-bit chunks returned */
586 ofs += nitems * format / 32;
587 } while (rem > 0);
590 * Deleting the property again tells the selection owner to send the
591 * next data chunk in the property.
593 XDeleteProperty(xw.dpy, xw.win, (int)property);
596 void
597 xclipcopy(void)
599 clipcopy(NULL);
602 void
603 selclear_(XEvent *e)
605 selclear();
608 void
609 selrequest(XEvent *e)
611 XSelectionRequestEvent *xsre;
612 XSelectionEvent xev;
613 Atom xa_targets, string, clipboard;
614 char *seltext;
616 xsre = (XSelectionRequestEvent *) e;
617 xev.type = SelectionNotify;
618 xev.requestor = xsre->requestor;
619 xev.selection = xsre->selection;
620 xev.target = xsre->target;
621 xev.time = xsre->time;
622 if (xsre->property == None)
623 xsre->property = xsre->target;
625 /* reject */
626 xev.property = None;
628 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
629 if (xsre->target == xa_targets) {
630 /* respond with the supported type */
631 string = xsel.xtarget;
632 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
633 XA_ATOM, 32, PropModeReplace,
634 (uchar *) &string, 1);
635 xev.property = xsre->property;
636 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
638 * xith XA_STRING non ascii characters may be incorrect in the
639 * requestor. It is not our problem, use utf8.
641 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
642 if (xsre->selection == XA_PRIMARY) {
643 seltext = xsel.primary;
644 } else if (xsre->selection == clipboard) {
645 seltext = xsel.clipboard;
646 } else {
647 fprintf(stderr,
648 "Unhandled clipboard selection 0x%lx\n",
649 xsre->selection);
650 return;
652 if (seltext != NULL) {
653 XChangeProperty(xsre->display, xsre->requestor,
654 xsre->property, xsre->target,
655 8, PropModeReplace,
656 (uchar *)seltext, strlen(seltext));
657 xev.property = xsre->property;
661 /* all done, send a notification to the listener */
662 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
663 fprintf(stderr, "Error sending SelectionNotify event\n");
666 void
667 setsel(char *str, Time t)
669 if (!str)
670 return;
672 free(xsel.primary);
673 xsel.primary = str;
675 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
676 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
677 selclear();
680 void
681 xsetsel(char *str)
683 setsel(str, CurrentTime);
686 void
687 brelease(XEvent *e)
689 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
690 mousereport(e);
691 return;
694 if (mouseaction(e, 1))
695 return;
696 if (e->xbutton.button == Button1)
697 mousesel(e, 1);
700 void
701 bmotion(XEvent *e)
703 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
704 mousereport(e);
705 return;
708 mousesel(e, 0);
711 void
712 cresize(int width, int height)
714 int col, row;
716 if (width != 0)
717 win.w = width;
718 if (height != 0)
719 win.h = height;
721 col = (win.w - 2 * borderpx) / win.cw;
722 row = (win.h - 2 * borderpx) / win.ch;
723 col = MAX(1, col);
724 row = MAX(1, row);
726 tresize(col, row);
727 xresize(col, row);
728 ttyresize(win.tw, win.th);
731 void
732 xresize(int col, int row)
734 win.tw = col * win.cw;
735 win.th = row * win.ch;
737 XFreePixmap(xw.dpy, xw.buf);
738 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
739 DefaultDepth(xw.dpy, xw.scr));
740 XftDrawChange(xw.draw, xw.buf);
741 xclear(0, 0, win.w, win.h);
743 /* resize to new width */
744 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
747 ushort
748 sixd_to_16bit(int x)
750 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
754 xloadcolor(int i, const char *name, Color *ncolor)
756 XRenderColor color = { .alpha = 0xffff };
758 if (!name) {
759 if (BETWEEN(i, 16, 255)) { /* 256 color */
760 if (i < 6*6*6+16) { /* same colors as xterm */
761 color.red = sixd_to_16bit( ((i-16)/36)%6 );
762 color.green = sixd_to_16bit( ((i-16)/6) %6 );
763 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
764 } else { /* greyscale */
765 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
766 color.green = color.blue = color.red;
768 return XftColorAllocValue(xw.dpy, xw.vis,
769 xw.cmap, &color, ncolor);
770 } else
771 name = colorname[i];
774 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
777 void
778 xloadcols(void)
780 int i;
781 static int loaded;
782 Color *cp;
784 if (loaded) {
785 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
786 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
787 } else {
788 dc.collen = MAX(LEN(colorname), 256);
789 dc.col = xmalloc(dc.collen * sizeof(Color));
792 for (i = 0; i < dc.collen; i++)
793 if (!xloadcolor(i, NULL, &dc.col[i])) {
794 if (colorname[i])
795 die("could not allocate color '%s'\n", colorname[i]);
796 else
797 die("could not allocate color %d\n", i);
799 loaded = 1;
803 xsetcolorname(int x, const char *name)
805 Color ncolor;
807 if (!BETWEEN(x, 0, dc.collen))
808 return 1;
810 if (!xloadcolor(x, name, &ncolor))
811 return 1;
813 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
814 dc.col[x] = ncolor;
816 return 0;
820 * Absolute coordinates.
822 void
823 xclear(int x1, int y1, int x2, int y2)
825 XftDrawRect(xw.draw,
826 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
827 x1, y1, x2-x1, y2-y1);
830 void
831 xhints(void)
833 XClassHint class = {opt_name ? opt_name : termname,
834 opt_class ? opt_class : termname};
835 XWMHints wm = {.flags = InputHint, .input = 1};
836 XSizeHints *sizeh;
838 sizeh = XAllocSizeHints();
840 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
841 sizeh->height = win.h;
842 sizeh->width = win.w;
843 sizeh->height_inc = win.ch;
844 sizeh->width_inc = win.cw;
845 sizeh->base_height = 2 * borderpx;
846 sizeh->base_width = 2 * borderpx;
847 sizeh->min_height = win.ch + 2 * borderpx;
848 sizeh->min_width = win.cw + 2 * borderpx;
849 if (xw.isfixed) {
850 sizeh->flags |= PMaxSize;
851 sizeh->min_width = sizeh->max_width = win.w;
852 sizeh->min_height = sizeh->max_height = win.h;
854 if (xw.gm & (XValue|YValue)) {
855 sizeh->flags |= USPosition | PWinGravity;
856 sizeh->x = xw.l;
857 sizeh->y = xw.t;
858 sizeh->win_gravity = xgeommasktogravity(xw.gm);
861 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
862 &class);
863 XFree(sizeh);
867 xgeommasktogravity(int mask)
869 switch (mask & (XNegative|YNegative)) {
870 case 0:
871 return NorthWestGravity;
872 case XNegative:
873 return NorthEastGravity;
874 case YNegative:
875 return SouthWestGravity;
878 return SouthEastGravity;
882 xloadfont(Font *f, FcPattern *pattern)
884 FcPattern *configured;
885 FcPattern *match;
886 FcResult result;
887 XGlyphInfo extents;
888 int wantattr, haveattr;
891 * Manually configure instead of calling XftMatchFont
892 * so that we can use the configured pattern for
893 * "missing glyph" lookups.
895 configured = FcPatternDuplicate(pattern);
896 if (!configured)
897 return 1;
899 FcConfigSubstitute(NULL, configured, FcMatchPattern);
900 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
902 match = FcFontMatch(NULL, configured, &result);
903 if (!match) {
904 FcPatternDestroy(configured);
905 return 1;
908 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
909 FcPatternDestroy(configured);
910 FcPatternDestroy(match);
911 return 1;
914 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
915 XftResultMatch)) {
917 * Check if xft was unable to find a font with the appropriate
918 * slant but gave us one anyway. Try to mitigate.
920 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
921 &haveattr) != XftResultMatch) || haveattr < wantattr) {
922 f->badslant = 1;
923 fputs("font slant does not match\n", stderr);
927 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
928 XftResultMatch)) {
929 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
930 &haveattr) != XftResultMatch) || haveattr != wantattr) {
931 f->badweight = 1;
932 fputs("font weight does not match\n", stderr);
936 XftTextExtentsUtf8(xw.dpy, f->match,
937 (const FcChar8 *) ascii_printable,
938 strlen(ascii_printable), &extents);
940 f->set = NULL;
941 f->pattern = configured;
943 f->ascent = f->match->ascent;
944 f->descent = f->match->descent;
945 f->lbearing = 0;
946 f->rbearing = f->match->max_advance_width;
948 f->height = f->ascent + f->descent;
949 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
951 return 0;
954 void
955 xloadfonts(const char *fontstr, double fontsize)
957 FcPattern *pattern;
958 double fontval;
960 if (fontstr[0] == '-')
961 pattern = XftXlfdParse(fontstr, False, False);
962 else
963 pattern = FcNameParse((const FcChar8 *)fontstr);
965 if (!pattern)
966 die("can't open font %s\n", fontstr);
968 if (fontsize > 1) {
969 FcPatternDel(pattern, FC_PIXEL_SIZE);
970 FcPatternDel(pattern, FC_SIZE);
971 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
972 usedfontsize = fontsize;
973 } else {
974 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
975 FcResultMatch) {
976 usedfontsize = fontval;
977 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
978 FcResultMatch) {
979 usedfontsize = -1;
980 } else {
982 * Default font size is 12, if none given. This is to
983 * have a known usedfontsize value.
985 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
986 usedfontsize = 12;
988 defaultfontsize = usedfontsize;
991 if (xloadfont(&dc.font, pattern))
992 die("can't open font %s\n", fontstr);
994 if (usedfontsize < 0) {
995 FcPatternGetDouble(dc.font.match->pattern,
996 FC_PIXEL_SIZE, 0, &fontval);
997 usedfontsize = fontval;
998 if (fontsize == 0)
999 defaultfontsize = fontval;
1002 /* Setting character width and height. */
1003 win.cw = ceilf(dc.font.width * cwscale);
1004 win.ch = ceilf(dc.font.height * chscale);
1006 FcPatternDel(pattern, FC_SLANT);
1007 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1008 if (xloadfont(&dc.ifont, pattern))
1009 die("can't open font %s\n", fontstr);
1011 FcPatternDel(pattern, FC_WEIGHT);
1012 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1013 if (xloadfont(&dc.ibfont, pattern))
1014 die("can't open font %s\n", fontstr);
1016 FcPatternDel(pattern, FC_SLANT);
1017 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1018 if (xloadfont(&dc.bfont, pattern))
1019 die("can't open font %s\n", fontstr);
1021 FcPatternDestroy(pattern);
1024 void
1025 xunloadfont(Font *f)
1027 XftFontClose(xw.dpy, f->match);
1028 FcPatternDestroy(f->pattern);
1029 if (f->set)
1030 FcFontSetDestroy(f->set);
1033 void
1034 xunloadfonts(void)
1036 /* Free the loaded fonts in the font cache. */
1037 while (frclen > 0)
1038 XftFontClose(xw.dpy, frc[--frclen].font);
1040 xunloadfont(&dc.font);
1041 xunloadfont(&dc.bfont);
1042 xunloadfont(&dc.ifont);
1043 xunloadfont(&dc.ibfont);
1047 ximopen(Display *dpy)
1049 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1050 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1052 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1053 if (xw.ime.xim == NULL)
1054 return 0;
1056 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1057 fprintf(stderr, "XSetIMValues: "
1058 "Could not set XNDestroyCallback.\n");
1060 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1061 NULL);
1063 if (xw.ime.xic == NULL) {
1064 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1065 XIMPreeditNothing | XIMStatusNothing,
1066 XNClientWindow, xw.win,
1067 XNDestroyCallback, &icdestroy,
1068 NULL);
1070 if (xw.ime.xic == NULL)
1071 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1073 return 1;
1076 void
1077 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1079 if (ximopen(dpy))
1080 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1081 ximinstantiate, NULL);
1084 void
1085 ximdestroy(XIM xim, XPointer client, XPointer call)
1087 xw.ime.xim = NULL;
1088 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1089 ximinstantiate, NULL);
1090 XFree(xw.ime.spotlist);
1094 xicdestroy(XIC xim, XPointer client, XPointer call)
1096 xw.ime.xic = NULL;
1097 return 1;
1100 void
1101 xinit(int cols, int rows)
1103 XGCValues gcvalues;
1104 Cursor cursor;
1105 Window parent;
1106 pid_t thispid = getpid();
1107 XColor xmousefg, xmousebg;
1109 if (!(xw.dpy = XOpenDisplay(NULL)))
1110 die("can't open display\n");
1111 xw.scr = XDefaultScreen(xw.dpy);
1112 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1114 /* font */
1115 if (!FcInit())
1116 die("could not init fontconfig.\n");
1118 usedfont = (opt_font == NULL)? font : opt_font;
1119 xloadfonts(usedfont, 0);
1121 /* colors */
1122 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1123 xloadcols();
1125 /* adjust fixed window geometry */
1126 win.w = 2 * borderpx + cols * win.cw;
1127 win.h = 2 * borderpx + rows * win.ch;
1128 if (xw.gm & XNegative)
1129 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1130 if (xw.gm & YNegative)
1131 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1133 /* Events */
1134 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1135 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1136 xw.attrs.bit_gravity = NorthWestGravity;
1137 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1138 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1139 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1140 xw.attrs.colormap = xw.cmap;
1142 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1143 parent = XRootWindow(xw.dpy, xw.scr);
1144 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1145 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1146 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1147 | CWEventMask | CWColormap, &xw.attrs);
1149 memset(&gcvalues, 0, sizeof(gcvalues));
1150 gcvalues.graphics_exposures = False;
1151 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1152 &gcvalues);
1153 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1154 DefaultDepth(xw.dpy, xw.scr));
1155 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1156 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1158 /* font spec buffer */
1159 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1161 /* Xft rendering context */
1162 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1164 /* input methods */
1165 if (!ximopen(xw.dpy)) {
1166 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1167 ximinstantiate, NULL);
1170 /* white cursor, black outline */
1171 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1172 XDefineCursor(xw.dpy, xw.win, cursor);
1174 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1175 xmousefg.red = 0xffff;
1176 xmousefg.green = 0xffff;
1177 xmousefg.blue = 0xffff;
1180 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1181 xmousebg.red = 0x0000;
1182 xmousebg.green = 0x0000;
1183 xmousebg.blue = 0x0000;
1186 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1188 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1189 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1190 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1191 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1192 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1194 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1195 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1196 PropModeReplace, (uchar *)&thispid, 1);
1198 win.mode = MODE_NUMLOCK;
1199 resettitle();
1200 xhints();
1201 XMapWindow(xw.dpy, xw.win);
1202 XSync(xw.dpy, False);
1204 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1205 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1206 xsel.primary = NULL;
1207 xsel.clipboard = NULL;
1208 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1209 if (xsel.xtarget == None)
1210 xsel.xtarget = XA_STRING;
1214 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1216 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1217 ushort mode, prevmode = USHRT_MAX;
1218 Font *font = &dc.font;
1219 int frcflags = FRC_NORMAL;
1220 float runewidth = win.cw;
1221 Rune rune;
1222 FT_UInt glyphidx;
1223 FcResult fcres;
1224 FcPattern *fcpattern, *fontpattern;
1225 FcFontSet *fcsets[] = { NULL };
1226 FcCharSet *fccharset;
1227 int i, f, numspecs = 0;
1229 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1230 /* Fetch rune and mode for current glyph. */
1231 rune = glyphs[i].u;
1232 mode = glyphs[i].mode;
1234 /* Skip dummy wide-character spacing. */
1235 if (mode == ATTR_WDUMMY)
1236 continue;
1238 /* Determine font for glyph if different from previous glyph. */
1239 if (prevmode != mode) {
1240 prevmode = mode;
1241 font = &dc.font;
1242 frcflags = FRC_NORMAL;
1243 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1244 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1245 font = &dc.ibfont;
1246 frcflags = FRC_ITALICBOLD;
1247 } else if (mode & ATTR_ITALIC) {
1248 font = &dc.ifont;
1249 frcflags = FRC_ITALIC;
1250 } else if (mode & ATTR_BOLD) {
1251 font = &dc.bfont;
1252 frcflags = FRC_BOLD;
1254 yp = winy + font->ascent;
1257 /* Lookup character index with default font. */
1258 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1259 if (glyphidx) {
1260 specs[numspecs].font = font->match;
1261 specs[numspecs].glyph = glyphidx;
1262 specs[numspecs].x = (short)xp;
1263 specs[numspecs].y = (short)yp;
1264 xp += runewidth;
1265 numspecs++;
1266 continue;
1269 /* Fallback on font cache, search the font cache for match. */
1270 for (f = 0; f < frclen; f++) {
1271 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1272 /* Everything correct. */
1273 if (glyphidx && frc[f].flags == frcflags)
1274 break;
1275 /* We got a default font for a not found glyph. */
1276 if (!glyphidx && frc[f].flags == frcflags
1277 && frc[f].unicodep == rune) {
1278 break;
1282 /* Nothing was found. Use fontconfig to find matching font. */
1283 if (f >= frclen) {
1284 if (!font->set)
1285 font->set = FcFontSort(0, font->pattern,
1286 1, 0, &fcres);
1287 fcsets[0] = font->set;
1290 * Nothing was found in the cache. Now use
1291 * some dozen of Fontconfig calls to get the
1292 * font for one single character.
1294 * Xft and fontconfig are design failures.
1296 fcpattern = FcPatternDuplicate(font->pattern);
1297 fccharset = FcCharSetCreate();
1299 FcCharSetAddChar(fccharset, rune);
1300 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1301 fccharset);
1302 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1304 FcConfigSubstitute(0, fcpattern,
1305 FcMatchPattern);
1306 FcDefaultSubstitute(fcpattern);
1308 fontpattern = FcFontSetMatch(0, fcsets, 1,
1309 fcpattern, &fcres);
1311 /* Allocate memory for the new cache entry. */
1312 if (frclen >= frccap) {
1313 frccap += 16;
1314 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1317 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1318 fontpattern);
1319 if (!frc[frclen].font)
1320 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1321 strerror(errno));
1322 frc[frclen].flags = frcflags;
1323 frc[frclen].unicodep = rune;
1325 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1327 f = frclen;
1328 frclen++;
1330 FcPatternDestroy(fcpattern);
1331 FcCharSetDestroy(fccharset);
1334 specs[numspecs].font = frc[f].font;
1335 specs[numspecs].glyph = glyphidx;
1336 specs[numspecs].x = (short)xp;
1337 specs[numspecs].y = (short)yp;
1338 xp += runewidth;
1339 numspecs++;
1342 return numspecs;
1345 void
1346 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1348 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1349 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1350 width = charlen * win.cw;
1351 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1352 XRenderColor colfg, colbg;
1353 XRectangle r;
1355 /* Fallback on color display for attributes not supported by the font */
1356 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1357 if (dc.ibfont.badslant || dc.ibfont.badweight)
1358 base.fg = defaultattr;
1359 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1360 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1361 base.fg = defaultattr;
1364 if (IS_TRUECOL(base.fg)) {
1365 colfg.alpha = 0xffff;
1366 colfg.red = TRUERED(base.fg);
1367 colfg.green = TRUEGREEN(base.fg);
1368 colfg.blue = TRUEBLUE(base.fg);
1369 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1370 fg = &truefg;
1371 } else {
1372 fg = &dc.col[base.fg];
1375 if (IS_TRUECOL(base.bg)) {
1376 colbg.alpha = 0xffff;
1377 colbg.green = TRUEGREEN(base.bg);
1378 colbg.red = TRUERED(base.bg);
1379 colbg.blue = TRUEBLUE(base.bg);
1380 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1381 bg = &truebg;
1382 } else {
1383 bg = &dc.col[base.bg];
1386 /* Change basic system colors [0-7] to bright system colors [8-15] */
1387 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1388 fg = &dc.col[base.fg + 8];
1390 if (IS_SET(MODE_REVERSE)) {
1391 if (fg == &dc.col[defaultfg]) {
1392 fg = &dc.col[defaultbg];
1393 } else {
1394 colfg.red = ~fg->color.red;
1395 colfg.green = ~fg->color.green;
1396 colfg.blue = ~fg->color.blue;
1397 colfg.alpha = fg->color.alpha;
1398 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1399 &revfg);
1400 fg = &revfg;
1403 if (bg == &dc.col[defaultbg]) {
1404 bg = &dc.col[defaultfg];
1405 } else {
1406 colbg.red = ~bg->color.red;
1407 colbg.green = ~bg->color.green;
1408 colbg.blue = ~bg->color.blue;
1409 colbg.alpha = bg->color.alpha;
1410 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1411 &revbg);
1412 bg = &revbg;
1416 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1417 colfg.red = fg->color.red / 2;
1418 colfg.green = fg->color.green / 2;
1419 colfg.blue = fg->color.blue / 2;
1420 colfg.alpha = fg->color.alpha;
1421 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1422 fg = &revfg;
1425 if (base.mode & ATTR_REVERSE) {
1426 temp = fg;
1427 fg = bg;
1428 bg = temp;
1431 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1432 fg = bg;
1434 if (base.mode & ATTR_INVISIBLE)
1435 fg = bg;
1437 /* Intelligent cleaning up of the borders. */
1438 if (x == 0) {
1439 xclear(0, (y == 0)? 0 : winy, borderpx,
1440 winy + win.ch +
1441 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1443 if (winx + width >= borderpx + win.tw) {
1444 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1445 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1447 if (y == 0)
1448 xclear(winx, 0, winx + width, borderpx);
1449 if (winy + win.ch >= borderpx + win.th)
1450 xclear(winx, winy + win.ch, winx + width, win.h);
1452 /* Clean up the region we want to draw to. */
1453 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1455 /* Set the clip region because Xft is sometimes dirty. */
1456 r.x = 0;
1457 r.y = 0;
1458 r.height = win.ch;
1459 r.width = width;
1460 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1462 /* Render the glyphs. */
1463 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1465 /* Render underline and strikethrough. */
1466 if (base.mode & ATTR_UNDERLINE) {
1467 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1468 width, 1);
1471 if (base.mode & ATTR_STRUCK) {
1472 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1473 width, 1);
1476 /* Reset clip to none. */
1477 XftDrawSetClip(xw.draw, 0);
1480 void
1481 xdrawglyph(Glyph g, int x, int y)
1483 int numspecs;
1484 XftGlyphFontSpec spec;
1486 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1487 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1490 void
1491 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1493 Color drawcol;
1495 /* remove the old cursor */
1496 if (selected(ox, oy))
1497 og.mode ^= ATTR_REVERSE;
1498 xdrawglyph(og, ox, oy);
1500 if (IS_SET(MODE_HIDE))
1501 return;
1504 * Select the right color for the right mode.
1506 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1508 if (IS_SET(MODE_REVERSE)) {
1509 g.mode |= ATTR_REVERSE;
1510 g.bg = defaultfg;
1511 if (selected(cx, cy)) {
1512 drawcol = dc.col[defaultcs];
1513 g.fg = defaultrcs;
1514 } else {
1515 drawcol = dc.col[defaultrcs];
1516 g.fg = defaultcs;
1518 } else {
1519 if (selected(cx, cy)) {
1520 g.fg = defaultfg;
1521 g.bg = defaultrcs;
1522 } else {
1523 g.fg = defaultbg;
1524 g.bg = defaultcs;
1526 drawcol = dc.col[g.bg];
1529 /* draw the new one */
1530 if (IS_SET(MODE_FOCUSED)) {
1531 switch (win.cursor) {
1532 case 7: /* st extension */
1533 g.u = 0x2603; /* snowman (U+2603) */
1534 /* FALLTHROUGH */
1535 case 0: /* Blinking Block */
1536 case 1: /* Blinking Block (Default) */
1537 case 2: /* Steady Block */
1538 xdrawglyph(g, cx, cy);
1539 break;
1540 case 3: /* Blinking Underline */
1541 case 4: /* Steady Underline */
1542 XftDrawRect(xw.draw, &drawcol,
1543 borderpx + cx * win.cw,
1544 borderpx + (cy + 1) * win.ch - \
1545 cursorthickness,
1546 win.cw, cursorthickness);
1547 break;
1548 case 5: /* Blinking bar */
1549 case 6: /* Steady bar */
1550 XftDrawRect(xw.draw, &drawcol,
1551 borderpx + cx * win.cw,
1552 borderpx + cy * win.ch,
1553 cursorthickness, win.ch);
1554 break;
1556 } else {
1557 XftDrawRect(xw.draw, &drawcol,
1558 borderpx + cx * win.cw,
1559 borderpx + cy * win.ch,
1560 win.cw - 1, 1);
1561 XftDrawRect(xw.draw, &drawcol,
1562 borderpx + cx * win.cw,
1563 borderpx + cy * win.ch,
1564 1, win.ch - 1);
1565 XftDrawRect(xw.draw, &drawcol,
1566 borderpx + (cx + 1) * win.cw - 1,
1567 borderpx + cy * win.ch,
1568 1, win.ch - 1);
1569 XftDrawRect(xw.draw, &drawcol,
1570 borderpx + cx * win.cw,
1571 borderpx + (cy + 1) * win.ch - 1,
1572 win.cw, 1);
1576 void
1577 xsetenv(void)
1579 char buf[sizeof(long) * 8 + 1];
1581 snprintf(buf, sizeof(buf), "%lu", xw.win);
1582 setenv("WINDOWID", buf, 1);
1585 void
1586 xseticontitle(char *p)
1588 XTextProperty prop;
1589 DEFAULT(p, opt_title);
1591 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1592 &prop) != Success)
1593 return;
1594 XSetWMIconName(xw.dpy, xw.win, &prop);
1595 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1596 XFree(prop.value);
1599 void
1600 xsettitle(char *p)
1602 XTextProperty prop;
1603 DEFAULT(p, opt_title);
1605 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1606 &prop) != Success)
1607 return;
1608 XSetWMName(xw.dpy, xw.win, &prop);
1609 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1610 XFree(prop.value);
1614 xstartdraw(void)
1616 return IS_SET(MODE_VISIBLE);
1619 void
1620 xdrawline(Line line, int x1, int y1, int x2)
1622 int i, x, ox, numspecs;
1623 Glyph base, new;
1624 XftGlyphFontSpec *specs = xw.specbuf;
1626 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1627 i = ox = 0;
1628 for (x = x1; x < x2 && i < numspecs; x++) {
1629 new = line[x];
1630 if (new.mode == ATTR_WDUMMY)
1631 continue;
1632 if (selected(x, y1))
1633 new.mode ^= ATTR_REVERSE;
1634 if (i > 0 && ATTRCMP(base, new)) {
1635 xdrawglyphfontspecs(specs, base, i, ox, y1);
1636 specs += i;
1637 numspecs -= i;
1638 i = 0;
1640 if (i == 0) {
1641 ox = x;
1642 base = new;
1644 i++;
1646 if (i > 0)
1647 xdrawglyphfontspecs(specs, base, i, ox, y1);
1650 void
1651 xfinishdraw(void)
1653 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1654 win.h, 0, 0);
1655 XSetForeground(xw.dpy, dc.gc,
1656 dc.col[IS_SET(MODE_REVERSE)?
1657 defaultfg : defaultbg].pixel);
1660 void
1661 xximspot(int x, int y)
1663 if (xw.ime.xic == NULL)
1664 return;
1666 xw.ime.spot.x = borderpx + x * win.cw;
1667 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1669 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1672 void
1673 expose(XEvent *ev)
1675 redraw();
1678 void
1679 visibility(XEvent *ev)
1681 XVisibilityEvent *e = &ev->xvisibility;
1683 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1686 void
1687 unmap(XEvent *ev)
1689 win.mode &= ~MODE_VISIBLE;
1692 void
1693 xsetpointermotion(int set)
1695 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1696 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1699 void
1700 xsetmode(int set, unsigned int flags)
1702 int mode = win.mode;
1703 MODBIT(win.mode, set, flags);
1704 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1705 redraw();
1709 xsetcursor(int cursor)
1711 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
1712 return 1;
1713 win.cursor = cursor;
1714 return 0;
1717 void
1718 xseturgency(int add)
1720 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1722 MODBIT(h->flags, add, XUrgencyHint);
1723 XSetWMHints(xw.dpy, xw.win, h);
1724 XFree(h);
1727 void
1728 xbell(void)
1730 if (!(IS_SET(MODE_FOCUSED)))
1731 xseturgency(1);
1732 if (bellvolume)
1733 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1736 void
1737 focus(XEvent *ev)
1739 XFocusChangeEvent *e = &ev->xfocus;
1741 if (e->mode == NotifyGrab)
1742 return;
1744 if (ev->type == FocusIn) {
1745 if (xw.ime.xic)
1746 XSetICFocus(xw.ime.xic);
1747 win.mode |= MODE_FOCUSED;
1748 xseturgency(0);
1749 if (IS_SET(MODE_FOCUS))
1750 ttywrite("\033[I", 3, 0);
1751 } else {
1752 if (xw.ime.xic)
1753 XUnsetICFocus(xw.ime.xic);
1754 win.mode &= ~MODE_FOCUSED;
1755 if (IS_SET(MODE_FOCUS))
1756 ttywrite("\033[O", 3, 0);
1761 match(uint mask, uint state)
1763 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1766 char*
1767 kmap(KeySym k, uint state)
1769 Key *kp;
1770 int i;
1772 /* Check for mapped keys out of X11 function keys. */
1773 for (i = 0; i < LEN(mappedkeys); i++) {
1774 if (mappedkeys[i] == k)
1775 break;
1777 if (i == LEN(mappedkeys)) {
1778 if ((k & 0xFFFF) < 0xFD00)
1779 return NULL;
1782 for (kp = key; kp < key + LEN(key); kp++) {
1783 if (kp->k != k)
1784 continue;
1786 if (!match(kp->mask, state))
1787 continue;
1789 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1790 continue;
1791 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1792 continue;
1794 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1795 continue;
1797 return kp->s;
1800 return NULL;
1803 void
1804 kpress(XEvent *ev)
1806 XKeyEvent *e = &ev->xkey;
1807 KeySym ksym;
1808 char buf[64], *customkey;
1809 int len;
1810 Rune c;
1811 Status status;
1812 Shortcut *bp;
1814 if (IS_SET(MODE_KBDLOCK))
1815 return;
1817 if (xw.ime.xic)
1818 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1819 else
1820 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1821 /* 1. shortcuts */
1822 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1823 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1824 bp->func(&(bp->arg));
1825 return;
1829 /* 2. custom keys from config.h */
1830 if ((customkey = kmap(ksym, e->state))) {
1831 ttywrite(customkey, strlen(customkey), 1);
1832 return;
1835 /* 3. composed string from input method */
1836 if (len == 0)
1837 return;
1838 if (len == 1 && e->state & Mod1Mask) {
1839 if (IS_SET(MODE_8BIT)) {
1840 if (*buf < 0177) {
1841 c = *buf | 0x80;
1842 len = utf8encode(c, buf);
1844 } else {
1845 buf[1] = buf[0];
1846 buf[0] = '\033';
1847 len = 2;
1850 ttywrite(buf, len, 1);
1853 void
1854 cmessage(XEvent *e)
1857 * See xembed specs
1858 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1860 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1861 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1862 win.mode |= MODE_FOCUSED;
1863 xseturgency(0);
1864 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1865 win.mode &= ~MODE_FOCUSED;
1867 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1868 ttyhangup();
1869 exit(0);
1873 void
1874 resize(XEvent *e)
1876 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1877 return;
1879 cresize(e->xconfigure.width, e->xconfigure.height);
1882 void
1883 run(void)
1885 XEvent ev;
1886 int w = win.w, h = win.h;
1887 fd_set rfd;
1888 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1889 struct timespec seltv, *tv, now, lastblink, trigger;
1890 double timeout;
1892 /* Waiting for window mapping */
1893 do {
1894 XNextEvent(xw.dpy, &ev);
1896 * This XFilterEvent call is required because of XOpenIM. It
1897 * does filter out the key event and some client message for
1898 * the input method too.
1900 if (XFilterEvent(&ev, None))
1901 continue;
1902 if (ev.type == ConfigureNotify) {
1903 w = ev.xconfigure.width;
1904 h = ev.xconfigure.height;
1906 } while (ev.type != MapNotify);
1908 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1909 cresize(w, h);
1911 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1912 FD_ZERO(&rfd);
1913 FD_SET(ttyfd, &rfd);
1914 FD_SET(xfd, &rfd);
1916 if (XPending(xw.dpy))
1917 timeout = 0; /* existing events might not set xfd */
1919 seltv.tv_sec = timeout / 1E3;
1920 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1921 tv = timeout >= 0 ? &seltv : NULL;
1923 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1924 if (errno == EINTR)
1925 continue;
1926 die("select failed: %s\n", strerror(errno));
1928 clock_gettime(CLOCK_MONOTONIC, &now);
1930 if (FD_ISSET(ttyfd, &rfd))
1931 ttyread();
1933 xev = 0;
1934 while (XPending(xw.dpy)) {
1935 xev = 1;
1936 XNextEvent(xw.dpy, &ev);
1937 if (XFilterEvent(&ev, None))
1938 continue;
1939 if (handler[ev.type])
1940 (handler[ev.type])(&ev);
1944 * To reduce flicker and tearing, when new content or event
1945 * triggers drawing, we first wait a bit to ensure we got
1946 * everything, and if nothing new arrives - we draw.
1947 * We start with trying to wait minlatency ms. If more content
1948 * arrives sooner, we retry with shorter and shorter periods,
1949 * and eventually draw even without idle after maxlatency ms.
1950 * Typically this results in low latency while interacting,
1951 * maximum latency intervals during `cat huge.txt`, and perfect
1952 * sync with periodic updates from animations/key-repeats/etc.
1954 if (FD_ISSET(ttyfd, &rfd) || xev) {
1955 if (!drawing) {
1956 trigger = now;
1957 drawing = 1;
1959 timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1960 / maxlatency * minlatency;
1961 if (timeout > 0)
1962 continue; /* we have time, try to find idle */
1965 /* idle detected or maxlatency exhausted -> draw */
1966 timeout = -1;
1967 if (blinktimeout && tattrset(ATTR_BLINK)) {
1968 timeout = blinktimeout - TIMEDIFF(now, lastblink);
1969 if (timeout <= 0) {
1970 if (-timeout > blinktimeout) /* start visible */
1971 win.mode |= MODE_BLINK;
1972 win.mode ^= MODE_BLINK;
1973 tsetdirtattr(ATTR_BLINK);
1974 lastblink = now;
1975 timeout = blinktimeout;
1979 draw();
1980 XFlush(xw.dpy);
1981 drawing = 0;
1985 void
1986 usage(void)
1988 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1989 " [-n name] [-o file]\n"
1990 " [-T title] [-t title] [-w windowid]"
1991 " [[-e] command [args ...]]\n"
1992 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1993 " [-n name] [-o file]\n"
1994 " [-T title] [-t title] [-w windowid] -l line"
1995 " [stty_args ...]\n", argv0, argv0);
1999 main(int argc, char *argv[])
2001 xw.l = xw.t = 0;
2002 xw.isfixed = False;
2003 xsetcursor(cursorshape);
2005 ARGBEGIN {
2006 case 'a':
2007 allowaltscreen = 0;
2008 break;
2009 case 'c':
2010 opt_class = EARGF(usage());
2011 break;
2012 case 'e':
2013 if (argc > 0)
2014 --argc, ++argv;
2015 goto run;
2016 case 'f':
2017 opt_font = EARGF(usage());
2018 break;
2019 case 'g':
2020 xw.gm = XParseGeometry(EARGF(usage()),
2021 &xw.l, &xw.t, &cols, &rows);
2022 break;
2023 case 'i':
2024 xw.isfixed = 1;
2025 break;
2026 case 'o':
2027 opt_io = EARGF(usage());
2028 break;
2029 case 'l':
2030 opt_line = EARGF(usage());
2031 break;
2032 case 'n':
2033 opt_name = EARGF(usage());
2034 break;
2035 case 't':
2036 case 'T':
2037 opt_title = EARGF(usage());
2038 break;
2039 case 'w':
2040 opt_embed = EARGF(usage());
2041 break;
2042 case 'v':
2043 die("%s " VERSION "\n", argv0);
2044 break;
2045 default:
2046 usage();
2047 } ARGEND;
2049 run:
2050 if (argc > 0) /* eat all remaining arguments */
2051 opt_cmd = argv;
2053 if (!opt_title)
2054 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2056 setlocale(LC_CTYPE, "");
2057 XSetLocaleModifiers("");
2058 cols = MAX(cols, 1);
2059 rows = MAX(rows, 1);
2060 tnew(cols, rows);
2061 xinit(cols, rows);
2062 xsetenv();
2063 selinit();
2064 run();
2066 return 0;