applied blinking cursor
[st.git] / x.c
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>
17 #include <X11/Xresource.h>
18
19 char *argv0;
20 #include "arg.h"
21 #include "st.h"
22 #include "win.h"
23
24 /* types used in config.h */
25 typedef struct {
26         uint mod;
27         KeySym keysym;
28         void (*func)(const Arg *);
29         const Arg arg;
30 } Shortcut;
31
32 typedef struct {
33         uint mod;
34         uint button;
35         void (*func)(const Arg *);
36         const Arg arg;
37         uint  release;
38 } MouseShortcut;
39
40 typedef struct {
41         KeySym k;
42         uint mask;
43         char *s;
44         /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
45         signed char appkey;    /* application keypad */
46         signed char appcursor; /* application cursor */
47 } Key;
48
49 /* Xresources preferences */
50 enum resource_type {
51         STRING = 0,
52         INTEGER = 1,
53         FLOAT = 2
54 };
55
56 typedef struct {
57         char *name;
58         enum resource_type type;
59         void *dst;
60 } ResourcePref;
61
62 /* X modifiers */
63 #define XK_ANY_MOD    UINT_MAX
64 #define XK_NO_MOD     0
65 #define XK_SWITCH_MOD (1<<13)
66
67 /* function definitions used in config.h */
68 static void clipcopy(const Arg *);
69 static void clippaste(const Arg *);
70 static void numlock(const Arg *);
71 static void selpaste(const Arg *);
72 static void zoom(const Arg *);
73 static void zoomabs(const Arg *);
74 static void zoomreset(const Arg *);
75 static void ttysend(const Arg *);
76
77 /* config.h for applying patches and the configuration. */
78 #include "config.h"
79
80 /* XEMBED messages */
81 #define XEMBED_FOCUS_IN  4
82 #define XEMBED_FOCUS_OUT 5
83
84 /* macros */
85 #define IS_SET(flag)            ((win.mode & (flag)) != 0)
86 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
87 #define TRUEGREEN(x)            (((x) & 0xff00))
88 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
89
90 typedef XftDraw *Draw;
91 typedef XftColor Color;
92 typedef XftGlyphFontSpec GlyphFontSpec;
93
94 /* Purely graphic info */
95 typedef struct {
96         int tw, th; /* tty width and height */
97         int w, h; /* window width and height */
98         int ch; /* char height */
99         int cw; /* char width  */
100         int mode; /* window state/mode flags */
101         int cursor; /* cursor style */
102 } TermWindow;
103
104 typedef struct {
105         Display *dpy;
106         Colormap cmap;
107         Window win;
108         Drawable buf;
109         GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
110         Atom xembed, wmdeletewin, netwmname, netwmpid;
111         struct {
112                 XIM xim;
113                 XIC xic;
114                 XPoint spot;
115                 XVaNestedList spotlist;
116         } ime;
117         Draw draw;
118         Visual *vis;
119         XSetWindowAttributes attrs;
120         int scr;
121         int isfixed; /* is fixed geometry? */
122         int l, t; /* left and top offset */
123         int gm; /* geometry mask */
124 } XWindow;
125
126 typedef struct {
127         Atom xtarget;
128         char *primary, *clipboard;
129         struct timespec tclick1;
130         struct timespec tclick2;
131 } XSelection;
132
133 /* Font structure */
134 #define Font Font_
135 typedef struct {
136         int height;
137         int width;
138         int ascent;
139         int descent;
140         int badslant;
141         int badweight;
142         short lbearing;
143         short rbearing;
144         XftFont *match;
145         FcFontSet *set;
146         FcPattern *pattern;
147 } Font;
148
149 /* Drawing Context */
150 typedef struct {
151         Color *col;
152         size_t collen;
153         Font font, bfont, ifont, ibfont;
154         GC gc;
155 } DC;
156
157 static inline ushort sixd_to_16bit(int);
158 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
159 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
160 static void xdrawglyph(Glyph, int, int);
161 static void xclear(int, int, int, int);
162 static int xgeommasktogravity(int);
163 static int ximopen(Display *);
164 static void ximinstantiate(Display *, XPointer, XPointer);
165 static void ximdestroy(XIM, XPointer, XPointer);
166 static int xicdestroy(XIC, XPointer, XPointer);
167 static void xinit(int, int);
168 static void cresize(int, int);
169 static void xresize(int, int);
170 static void xhints(void);
171 static int xloadcolor(int, const char *, Color *);
172 static int xloadfont(Font *, FcPattern *);
173 static void xloadfonts(char *, double);
174 static void xunloadfont(Font *);
175 static void xunloadfonts(void);
176 static void xsetenv(void);
177 static void xseturgency(int);
178 static int evcol(XEvent *);
179 static int evrow(XEvent *);
180
181 static void expose(XEvent *);
182 static void visibility(XEvent *);
183 static void unmap(XEvent *);
184 static void kpress(XEvent *);
185 static void cmessage(XEvent *);
186 static void resize(XEvent *);
187 static void focus(XEvent *);
188 static uint buttonmask(uint);
189 static int mouseaction(XEvent *, uint);
190 static void brelease(XEvent *);
191 static void bpress(XEvent *);
192 static void bmotion(XEvent *);
193 static void propnotify(XEvent *);
194 static void selnotify(XEvent *);
195 static void selclear_(XEvent *);
196 static void selrequest(XEvent *);
197 static void setsel(char *, Time);
198 static void mousesel(XEvent *, int);
199 static void mousereport(XEvent *);
200 static char *kmap(KeySym, uint);
201 static int match(uint, uint);
202
203 static void run(void);
204 static void usage(void);
205
206 static void (*handler[LASTEvent])(XEvent *) = {
207         [KeyPress] = kpress,
208         [ClientMessage] = cmessage,
209         [ConfigureNotify] = resize,
210         [VisibilityNotify] = visibility,
211         [UnmapNotify] = unmap,
212         [Expose] = expose,
213         [FocusIn] = focus,
214         [FocusOut] = focus,
215         [MotionNotify] = bmotion,
216         [ButtonPress] = bpress,
217         [ButtonRelease] = brelease,
218 /*
219  * Uncomment if you want the selection to disappear when you select something
220  * different in another window.
221  */
222 /*      [SelectionClear] = selclear_, */
223         [SelectionNotify] = selnotify,
224 /*
225  * PropertyNotify is only turned on when there is some INCR transfer happening
226  * for the selection retrieval.
227  */
228         [PropertyNotify] = propnotify,
229         [SelectionRequest] = selrequest,
230 };
231
232 /* Globals */
233 static DC dc;
234 static XWindow xw;
235 static XSelection xsel;
236 static TermWindow win;
237
238 /* Font Ring Cache */
239 enum {
240         FRC_NORMAL,
241         FRC_ITALIC,
242         FRC_BOLD,
243         FRC_ITALICBOLD
244 };
245
246 typedef struct {
247         XftFont *font;
248         int flags;
249         Rune unicodep;
250 } Fontcache;
251
252 /* Fontcache is an array now. A new font will be appended to the array. */
253 static Fontcache *frc = NULL;
254 static int frclen = 0;
255 static int frccap = 0;
256 static char *usedfont = NULL;
257 static double usedfontsize = 0;
258 static double defaultfontsize = 0;
259
260 static char *opt_class = NULL;
261 static char **opt_cmd  = NULL;
262 static char *opt_embed = NULL;
263 static char *opt_font  = NULL;
264 static char *opt_io    = NULL;
265 static char *opt_line  = NULL;
266 static char *opt_name  = NULL;
267 static char *opt_title = NULL;
268
269 static int oldbutton = 3; /* button event on startup: 3 = release */
270 static int cursorblinks = 0;
271
272 void
273 clipcopy(const Arg *dummy)
274 {
275         Atom clipboard;
276
277         free(xsel.clipboard);
278         xsel.clipboard = NULL;
279
280         if (xsel.primary != NULL) {
281                 xsel.clipboard = xstrdup(xsel.primary);
282                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
283                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
284         }
285 }
286
287 void
288 clippaste(const Arg *dummy)
289 {
290         Atom clipboard;
291
292         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
293         XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
294                         xw.win, CurrentTime);
295 }
296
297 void
298 selpaste(const Arg *dummy)
299 {
300         XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
301                         xw.win, CurrentTime);
302 }
303
304 void
305 numlock(const Arg *dummy)
306 {
307         win.mode ^= MODE_NUMLOCK;
308 }
309
310 void
311 zoom(const Arg *arg)
312 {
313         Arg larg;
314
315         larg.f = usedfontsize + arg->f;
316         zoomabs(&larg);
317 }
318
319 void
320 zoomabs(const Arg *arg)
321 {
322         xunloadfonts();
323         xloadfonts(usedfont, arg->f);
324         cresize(0, 0);
325         redraw();
326         xhints();
327 }
328
329 void
330 zoomreset(const Arg *arg)
331 {
332         Arg larg;
333
334         if (defaultfontsize > 0) {
335                 larg.f = defaultfontsize;
336                 zoomabs(&larg);
337         }
338 }
339
340 void
341 ttysend(const Arg *arg)
342 {
343         ttywrite(arg->s, strlen(arg->s), 1);
344 }
345
346 int
347 evcol(XEvent *e)
348 {
349         int x = e->xbutton.x - borderpx;
350         LIMIT(x, 0, win.tw - 1);
351         return x / win.cw;
352 }
353
354 int
355 evrow(XEvent *e)
356 {
357         int y = e->xbutton.y - borderpx;
358         LIMIT(y, 0, win.th - 1);
359         return y / win.ch;
360 }
361
362 void
363 mousesel(XEvent *e, int done)
364 {
365         int type, seltype = SEL_REGULAR;
366         uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
367
368         for (type = 1; type < LEN(selmasks); ++type) {
369                 if (match(selmasks[type], state)) {
370                         seltype = type;
371                         break;
372                 }
373         }
374         selextend(evcol(e), evrow(e), seltype, done);
375         if (done)
376                 setsel(getsel(), e->xbutton.time);
377 }
378
379 void
380 mousereport(XEvent *e)
381 {
382         int len, x = evcol(e), y = evrow(e),
383             button = e->xbutton.button, state = e->xbutton.state;
384         char buf[40];
385         static int ox, oy;
386
387         /* from urxvt */
388         if (e->xbutton.type == MotionNotify) {
389                 if (x == ox && y == oy)
390                         return;
391                 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
392                         return;
393                 /* MOUSE_MOTION: no reporting if no button is pressed */
394                 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
395                         return;
396
397                 button = oldbutton + 32;
398                 ox = x;
399                 oy = y;
400         } else {
401                 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
402                         button = 3;
403                 } else {
404                         button -= Button1;
405                         if (button >= 3)
406                                 button += 64 - 3;
407                 }
408                 if (e->xbutton.type == ButtonPress) {
409                         oldbutton = button;
410                         ox = x;
411                         oy = y;
412                 } else if (e->xbutton.type == ButtonRelease) {
413                         oldbutton = 3;
414                         /* MODE_MOUSEX10: no button release reporting */
415                         if (IS_SET(MODE_MOUSEX10))
416                                 return;
417                         if (button == 64 || button == 65)
418                                 return;
419                 }
420         }
421
422         if (!IS_SET(MODE_MOUSEX10)) {
423                 button += ((state & ShiftMask  ) ? 4  : 0)
424                         + ((state & Mod4Mask   ) ? 8  : 0)
425                         + ((state & ControlMask) ? 16 : 0);
426         }
427
428         if (IS_SET(MODE_MOUSESGR)) {
429                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
430                                 button, x+1, y+1,
431                                 e->xbutton.type == ButtonRelease ? 'm' : 'M');
432         } else if (x < 223 && y < 223) {
433                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
434                                 32+button, 32+x+1, 32+y+1);
435         } else {
436                 return;
437         }
438
439         ttywrite(buf, len, 0);
440 }
441
442 uint
443 buttonmask(uint button)
444 {
445         return button == Button1 ? Button1Mask
446              : button == Button2 ? Button2Mask
447              : button == Button3 ? Button3Mask
448              : button == Button4 ? Button4Mask
449              : button == Button5 ? Button5Mask
450              : 0;
451 }
452
453 int
454 mouseaction(XEvent *e, uint release)
455 {
456         MouseShortcut *ms;
457
458         /* ignore Button<N>mask for Button<N> - it's set on release */
459         uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
460
461         for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
462                 if (ms->release == release &&
463                     ms->button == e->xbutton.button &&
464                     (match(ms->mod, state) ||  /* exact or forced */
465                      match(ms->mod, state & ~forcemousemod))) {
466                         ms->func(&(ms->arg));
467                         return 1;
468                 }
469         }
470
471         return 0;
472 }
473
474 void
475 bpress(XEvent *e)
476 {
477         struct timespec now;
478         int snap;
479
480         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
481                 mousereport(e);
482                 return;
483         }
484
485         if (mouseaction(e, 0))
486                 return;
487
488         if (e->xbutton.button == Button1) {
489                 /*
490                  * If the user clicks below predefined timeouts specific
491                  * snapping behaviour is exposed.
492                  */
493                 clock_gettime(CLOCK_MONOTONIC, &now);
494                 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
495                         snap = SNAP_LINE;
496                 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
497                         snap = SNAP_WORD;
498                 } else {
499                         snap = 0;
500                 }
501                 xsel.tclick2 = xsel.tclick1;
502                 xsel.tclick1 = now;
503
504                 selstart(evcol(e), evrow(e), snap);
505         }
506 }
507
508 void
509 propnotify(XEvent *e)
510 {
511         XPropertyEvent *xpev;
512         Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
513
514         xpev = &e->xproperty;
515         if (xpev->state == PropertyNewValue &&
516                         (xpev->atom == XA_PRIMARY ||
517                          xpev->atom == clipboard)) {
518                 selnotify(e);
519         }
520 }
521
522 void
523 selnotify(XEvent *e)
524 {
525         ulong nitems, ofs, rem;
526         int format;
527         uchar *data, *last, *repl;
528         Atom type, incratom, property = None;
529
530         incratom = XInternAtom(xw.dpy, "INCR", 0);
531
532         ofs = 0;
533         if (e->type == SelectionNotify)
534                 property = e->xselection.property;
535         else if (e->type == PropertyNotify)
536                 property = e->xproperty.atom;
537
538         if (property == None)
539                 return;
540
541         do {
542                 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
543                                         BUFSIZ/4, False, AnyPropertyType,
544                                         &type, &format, &nitems, &rem,
545                                         &data)) {
546                         fprintf(stderr, "Clipboard allocation failed\n");
547                         return;
548                 }
549
550                 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
551                         /*
552                          * If there is some PropertyNotify with no data, then
553                          * this is the signal of the selection owner that all
554                          * data has been transferred. We won't need to receive
555                          * PropertyNotify events anymore.
556                          */
557                         MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
558                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
559                                         &xw.attrs);
560                 }
561
562                 if (type == incratom) {
563                         /*
564                          * Activate the PropertyNotify events so we receive
565                          * when the selection owner does send us the next
566                          * chunk of data.
567                          */
568                         MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
569                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
570                                         &xw.attrs);
571
572                         /*
573                          * Deleting the property is the transfer start signal.
574                          */
575                         XDeleteProperty(xw.dpy, xw.win, (int)property);
576                         continue;
577                 }
578
579                 /*
580                  * As seen in getsel:
581                  * Line endings are inconsistent in the terminal and GUI world
582                  * copy and pasting. When receiving some selection data,
583                  * replace all '\n' with '\r'.
584                  * FIXME: Fix the computer world.
585                  */
586                 repl = data;
587                 last = data + nitems * format / 8;
588                 while ((repl = memchr(repl, '\n', last - repl))) {
589                         *repl++ = '\r';
590                 }
591
592                 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
593                         ttywrite("\033[200~", 6, 0);
594                 ttywrite((char *)data, nitems * format / 8, 1);
595                 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
596                         ttywrite("\033[201~", 6, 0);
597                 XFree(data);
598                 /* number of 32-bit chunks returned */
599                 ofs += nitems * format / 32;
600         } while (rem > 0);
601
602         /*
603          * Deleting the property again tells the selection owner to send the
604          * next data chunk in the property.
605          */
606         XDeleteProperty(xw.dpy, xw.win, (int)property);
607 }
608
609 void
610 xclipcopy(void)
611 {
612         clipcopy(NULL);
613 }
614
615 void
616 selclear_(XEvent *e)
617 {
618         selclear();
619 }
620
621 void
622 selrequest(XEvent *e)
623 {
624         XSelectionRequestEvent *xsre;
625         XSelectionEvent xev;
626         Atom xa_targets, string, clipboard;
627         char *seltext;
628
629         xsre = (XSelectionRequestEvent *) e;
630         xev.type = SelectionNotify;
631         xev.requestor = xsre->requestor;
632         xev.selection = xsre->selection;
633         xev.target = xsre->target;
634         xev.time = xsre->time;
635         if (xsre->property == None)
636                 xsre->property = xsre->target;
637
638         /* reject */
639         xev.property = None;
640
641         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
642         if (xsre->target == xa_targets) {
643                 /* respond with the supported type */
644                 string = xsel.xtarget;
645                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
646                                 XA_ATOM, 32, PropModeReplace,
647                                 (uchar *) &string, 1);
648                 xev.property = xsre->property;
649         } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
650                 /*
651                  * xith XA_STRING non ascii characters may be incorrect in the
652                  * requestor. It is not our problem, use utf8.
653                  */
654                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
655                 if (xsre->selection == XA_PRIMARY) {
656                         seltext = xsel.primary;
657                 } else if (xsre->selection == clipboard) {
658                         seltext = xsel.clipboard;
659                 } else {
660                         fprintf(stderr,
661                                 "Unhandled clipboard selection 0x%lx\n",
662                                 xsre->selection);
663                         return;
664                 }
665                 if (seltext != NULL) {
666                         XChangeProperty(xsre->display, xsre->requestor,
667                                         xsre->property, xsre->target,
668                                         8, PropModeReplace,
669                                         (uchar *)seltext, strlen(seltext));
670                         xev.property = xsre->property;
671                 }
672         }
673
674         /* all done, send a notification to the listener */
675         if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
676                 fprintf(stderr, "Error sending SelectionNotify event\n");
677 }
678
679 void
680 setsel(char *str, Time t)
681 {
682         if (!str)
683                 return;
684
685         free(xsel.primary);
686         xsel.primary = str;
687
688         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
689         if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
690                 selclear();
691 }
692
693 void
694 xsetsel(char *str)
695 {
696         setsel(str, CurrentTime);
697 }
698
699 void
700 brelease(XEvent *e)
701 {
702         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
703                 mousereport(e);
704                 return;
705         }
706
707         if (mouseaction(e, 1))
708                 return;
709         if (e->xbutton.button == Button1)
710                 mousesel(e, 1);
711 }
712
713 void
714 bmotion(XEvent *e)
715 {
716         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
717                 mousereport(e);
718                 return;
719         }
720
721         mousesel(e, 0);
722 }
723
724 void
725 cresize(int width, int height)
726 {
727         int col, row;
728
729         if (width != 0)
730                 win.w = width;
731         if (height != 0)
732                 win.h = height;
733
734         col = (win.w - 2 * borderpx) / win.cw;
735         row = (win.h - 2 * borderpx) / win.ch;
736         col = MAX(1, col);
737         row = MAX(1, row);
738
739         tresize(col, row);
740         xresize(col, row);
741         ttyresize(win.tw, win.th);
742 }
743
744 void
745 xresize(int col, int row)
746 {
747         win.tw = col * win.cw;
748         win.th = row * win.ch;
749
750         XFreePixmap(xw.dpy, xw.buf);
751         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
752                         DefaultDepth(xw.dpy, xw.scr));
753         XftDrawChange(xw.draw, xw.buf);
754         xclear(0, 0, win.w, win.h);
755
756         /* resize to new width */
757         xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
758 }
759
760 ushort
761 sixd_to_16bit(int x)
762 {
763         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
764 }
765
766 int
767 xloadcolor(int i, const char *name, Color *ncolor)
768 {
769         XRenderColor color = { .alpha = 0xffff };
770
771         if (!name) {
772                 if (BETWEEN(i, 16, 255)) { /* 256 color */
773                         if (i < 6*6*6+16) { /* same colors as xterm */
774                                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
775                                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
776                                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
777                         } else { /* greyscale */
778                                 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
779                                 color.green = color.blue = color.red;
780                         }
781                         return XftColorAllocValue(xw.dpy, xw.vis,
782                                                   xw.cmap, &color, ncolor);
783                 } else
784                         name = colorname[i];
785         }
786
787         return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
788 }
789
790 void
791 xloadcols(void)
792 {
793         int i;
794         static int loaded;
795         Color *cp;
796
797         if (loaded) {
798                 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
799                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
800         } else {
801                 dc.collen = MAX(LEN(colorname), 256);
802                 dc.col = xmalloc(dc.collen * sizeof(Color));
803         }
804
805         for (i = 0; i < dc.collen; i++)
806                 if (!xloadcolor(i, NULL, &dc.col[i])) {
807                         if (colorname[i])
808                                 die("could not allocate color '%s'\n", colorname[i]);
809                         else
810                                 die("could not allocate color %d\n", i);
811                 }
812         loaded = 1;
813 }
814
815 int
816 xsetcolorname(int x, const char *name)
817 {
818         Color ncolor;
819
820         if (!BETWEEN(x, 0, dc.collen))
821                 return 1;
822
823         if (!xloadcolor(x, name, &ncolor))
824                 return 1;
825
826         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
827         dc.col[x] = ncolor;
828
829         return 0;
830 }
831
832 /*
833  * Absolute coordinates.
834  */
835 void
836 xclear(int x1, int y1, int x2, int y2)
837 {
838         XftDrawRect(xw.draw,
839                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
840                         x1, y1, x2-x1, y2-y1);
841 }
842
843 void
844 xhints(void)
845 {
846         XClassHint class = {opt_name ? opt_name : "st",
847                             opt_class ? opt_class : "St"};
848         XWMHints wm = {.flags = InputHint, .input = 1};
849         XSizeHints *sizeh;
850
851         sizeh = XAllocSizeHints();
852
853         sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
854         sizeh->height = win.h;
855         sizeh->width = win.w;
856         sizeh->height_inc = win.ch;
857         sizeh->width_inc = win.cw;
858         sizeh->base_height = 2 * borderpx;
859         sizeh->base_width = 2 * borderpx;
860         sizeh->min_height = win.ch + 2 * borderpx;
861         sizeh->min_width = win.cw + 2 * borderpx;
862         if (xw.isfixed) {
863                 sizeh->flags |= PMaxSize;
864                 sizeh->min_width = sizeh->max_width = win.w;
865                 sizeh->min_height = sizeh->max_height = win.h;
866         }
867         if (xw.gm & (XValue|YValue)) {
868                 sizeh->flags |= USPosition | PWinGravity;
869                 sizeh->x = xw.l;
870                 sizeh->y = xw.t;
871                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
872         }
873
874         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
875                         &class);
876         XFree(sizeh);
877 }
878
879 int
880 xgeommasktogravity(int mask)
881 {
882         switch (mask & (XNegative|YNegative)) {
883         case 0:
884                 return NorthWestGravity;
885         case XNegative:
886                 return NorthEastGravity;
887         case YNegative:
888                 return SouthWestGravity;
889         }
890
891         return SouthEastGravity;
892 }
893
894 int
895 xloadfont(Font *f, FcPattern *pattern)
896 {
897         FcPattern *configured;
898         FcPattern *match;
899         FcResult result;
900         XGlyphInfo extents;
901         int wantattr, haveattr;
902
903         /*
904          * Manually configure instead of calling XftMatchFont
905          * so that we can use the configured pattern for
906          * "missing glyph" lookups.
907          */
908         configured = FcPatternDuplicate(pattern);
909         if (!configured)
910                 return 1;
911
912         FcConfigSubstitute(NULL, configured, FcMatchPattern);
913         XftDefaultSubstitute(xw.dpy, xw.scr, configured);
914
915         match = FcFontMatch(NULL, configured, &result);
916         if (!match) {
917                 FcPatternDestroy(configured);
918                 return 1;
919         }
920
921         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
922                 FcPatternDestroy(configured);
923                 FcPatternDestroy(match);
924                 return 1;
925         }
926
927         if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
928             XftResultMatch)) {
929                 /*
930                  * Check if xft was unable to find a font with the appropriate
931                  * slant but gave us one anyway. Try to mitigate.
932                  */
933                 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
934                     &haveattr) != XftResultMatch) || haveattr < wantattr) {
935                         f->badslant = 1;
936                         fputs("font slant does not match\n", stderr);
937                 }
938         }
939
940         if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
941             XftResultMatch)) {
942                 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
943                     &haveattr) != XftResultMatch) || haveattr != wantattr) {
944                         f->badweight = 1;
945                         fputs("font weight does not match\n", stderr);
946                 }
947         }
948
949         XftTextExtentsUtf8(xw.dpy, f->match,
950                 (const FcChar8 *) ascii_printable,
951                 strlen(ascii_printable), &extents);
952
953         f->set = NULL;
954         f->pattern = configured;
955
956         f->ascent = f->match->ascent;
957         f->descent = f->match->descent;
958         f->lbearing = 0;
959         f->rbearing = f->match->max_advance_width;
960
961         f->height = f->ascent + f->descent;
962         f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
963
964         return 0;
965 }
966
967 void
968 xloadfonts(char *fontstr, double fontsize)
969 {
970         FcPattern *pattern;
971         double fontval;
972
973         if (fontstr[0] == '-')
974                 pattern = XftXlfdParse(fontstr, False, False);
975         else
976                 pattern = FcNameParse((FcChar8 *)fontstr);
977
978         if (!pattern)
979                 die("can't open font %s\n", fontstr);
980
981         if (fontsize > 1) {
982                 FcPatternDel(pattern, FC_PIXEL_SIZE);
983                 FcPatternDel(pattern, FC_SIZE);
984                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
985                 usedfontsize = fontsize;
986         } else {
987                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
988                                 FcResultMatch) {
989                         usedfontsize = fontval;
990                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
991                                 FcResultMatch) {
992                         usedfontsize = -1;
993                 } else {
994                         /*
995                          * Default font size is 12, if none given. This is to
996                          * have a known usedfontsize value.
997                          */
998                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
999                         usedfontsize = 12;
1000                 }
1001                 defaultfontsize = usedfontsize;
1002         }
1003
1004         if (xloadfont(&dc.font, pattern))
1005                 die("can't open font %s\n", fontstr);
1006
1007         if (usedfontsize < 0) {
1008                 FcPatternGetDouble(dc.font.match->pattern,
1009                                    FC_PIXEL_SIZE, 0, &fontval);
1010                 usedfontsize = fontval;
1011                 if (fontsize == 0)
1012                         defaultfontsize = fontval;
1013         }
1014
1015         /* Setting character width and height. */
1016         win.cw = ceilf(dc.font.width * cwscale);
1017         win.ch = ceilf(dc.font.height * chscale);
1018
1019         FcPatternDel(pattern, FC_SLANT);
1020         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1021         if (xloadfont(&dc.ifont, pattern))
1022                 die("can't open font %s\n", fontstr);
1023
1024         FcPatternDel(pattern, FC_WEIGHT);
1025         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1026         if (xloadfont(&dc.ibfont, pattern))
1027                 die("can't open font %s\n", fontstr);
1028
1029         FcPatternDel(pattern, FC_SLANT);
1030         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1031         if (xloadfont(&dc.bfont, pattern))
1032                 die("can't open font %s\n", fontstr);
1033
1034         FcPatternDestroy(pattern);
1035 }
1036
1037 void
1038 xunloadfont(Font *f)
1039 {
1040         XftFontClose(xw.dpy, f->match);
1041         FcPatternDestroy(f->pattern);
1042         if (f->set)
1043                 FcFontSetDestroy(f->set);
1044 }
1045
1046 void
1047 xunloadfonts(void)
1048 {
1049         /* Free the loaded fonts in the font cache.  */
1050         while (frclen > 0)
1051                 XftFontClose(xw.dpy, frc[--frclen].font);
1052
1053         xunloadfont(&dc.font);
1054         xunloadfont(&dc.bfont);
1055         xunloadfont(&dc.ifont);
1056         xunloadfont(&dc.ibfont);
1057 }
1058
1059 int
1060 ximopen(Display *dpy)
1061 {
1062         XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1063         XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1064
1065         xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1066         if (xw.ime.xim == NULL)
1067                 return 0;
1068
1069         if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1070                 fprintf(stderr, "XSetIMValues: "
1071                                 "Could not set XNDestroyCallback.\n");
1072
1073         xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1074                                               NULL);
1075
1076         if (xw.ime.xic == NULL) {
1077                 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1078                                        XIMPreeditNothing | XIMStatusNothing,
1079                                        XNClientWindow, xw.win,
1080                                        XNDestroyCallback, &icdestroy,
1081                                        NULL);
1082         }
1083         if (xw.ime.xic == NULL)
1084                 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1085
1086         return 1;
1087 }
1088
1089 void
1090 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1091 {
1092         if (ximopen(dpy))
1093                 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1094                                                  ximinstantiate, NULL);
1095 }
1096
1097 void
1098 ximdestroy(XIM xim, XPointer client, XPointer call)
1099 {
1100         xw.ime.xim = NULL;
1101         XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1102                                        ximinstantiate, NULL);
1103         XFree(xw.ime.spotlist);
1104 }
1105
1106 int
1107 xicdestroy(XIC xim, XPointer client, XPointer call)
1108 {
1109         xw.ime.xic = NULL;
1110         return 1;
1111 }
1112
1113 void
1114 xinit(int cols, int rows)
1115 {
1116         XGCValues gcvalues;
1117         Cursor cursor;
1118         Window parent;
1119         pid_t thispid = getpid();
1120         XColor xmousefg, xmousebg;
1121
1122         xw.scr = XDefaultScreen(xw.dpy);
1123         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1124
1125         /* font */
1126         if (!FcInit())
1127                 die("could not init fontconfig.\n");
1128
1129         usedfont = (opt_font == NULL)? font : opt_font;
1130         xloadfonts(usedfont, 0);
1131
1132         /* colors */
1133         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1134         xloadcols();
1135
1136         /* adjust fixed window geometry */
1137         win.w = 2 * borderpx + cols * win.cw;
1138         win.h = 2 * borderpx + rows * win.ch;
1139         if (xw.gm & XNegative)
1140                 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1141         if (xw.gm & YNegative)
1142                 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1143
1144         /* Events */
1145         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1146         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1147         xw.attrs.bit_gravity = NorthWestGravity;
1148         xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1149                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1150                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1151         xw.attrs.colormap = xw.cmap;
1152
1153         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1154                 parent = XRootWindow(xw.dpy, xw.scr);
1155         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1156                         win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1157                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1158                         | CWEventMask | CWColormap, &xw.attrs);
1159
1160         memset(&gcvalues, 0, sizeof(gcvalues));
1161         gcvalues.graphics_exposures = False;
1162         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1163                         &gcvalues);
1164         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1165                         DefaultDepth(xw.dpy, xw.scr));
1166         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1167         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1168
1169         /* font spec buffer */
1170         xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1171
1172         /* Xft rendering context */
1173         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1174
1175         /* input methods */
1176         if (!ximopen(xw.dpy)) {
1177                 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1178                                                ximinstantiate, NULL);
1179         }
1180
1181         /* white cursor, black outline */
1182         cursor = XCreateFontCursor(xw.dpy, mouseshape);
1183         XDefineCursor(xw.dpy, xw.win, cursor);
1184
1185         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1186                 xmousefg.red   = 0xffff;
1187                 xmousefg.green = 0xffff;
1188                 xmousefg.blue  = 0xffff;
1189         }
1190
1191         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1192                 xmousebg.red   = 0x0000;
1193                 xmousebg.green = 0x0000;
1194                 xmousebg.blue  = 0x0000;
1195         }
1196
1197         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1198
1199         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1200         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1201         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1202         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1203
1204         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1205         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1206                         PropModeReplace, (uchar *)&thispid, 1);
1207
1208         win.mode = MODE_NUMLOCK;
1209         resettitle();
1210         xhints();
1211         XMapWindow(xw.dpy, xw.win);
1212         XSync(xw.dpy, False);
1213
1214         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1215         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1216         xsel.primary = NULL;
1217         xsel.clipboard = NULL;
1218         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1219         if (xsel.xtarget == None)
1220                 xsel.xtarget = XA_STRING;
1221 }
1222
1223 int
1224 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1225 {
1226         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1227         ushort mode, prevmode = USHRT_MAX;
1228         Font *font = &dc.font;
1229         int frcflags = FRC_NORMAL;
1230         float runewidth = win.cw;
1231         Rune rune;
1232         FT_UInt glyphidx;
1233         FcResult fcres;
1234         FcPattern *fcpattern, *fontpattern;
1235         FcFontSet *fcsets[] = { NULL };
1236         FcCharSet *fccharset;
1237         int i, f, numspecs = 0;
1238
1239         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1240                 /* Fetch rune and mode for current glyph. */
1241                 rune = glyphs[i].u;
1242                 mode = glyphs[i].mode;
1243
1244                 /* Skip dummy wide-character spacing. */
1245                 if (mode == ATTR_WDUMMY)
1246                         continue;
1247
1248                 /* Determine font for glyph if different from previous glyph. */
1249                 if (prevmode != mode) {
1250                         prevmode = mode;
1251                         font = &dc.font;
1252                         frcflags = FRC_NORMAL;
1253                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1254                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1255                                 font = &dc.ibfont;
1256                                 frcflags = FRC_ITALICBOLD;
1257                         } else if (mode & ATTR_ITALIC) {
1258                                 font = &dc.ifont;
1259                                 frcflags = FRC_ITALIC;
1260                         } else if (mode & ATTR_BOLD) {
1261                                 font = &dc.bfont;
1262                                 frcflags = FRC_BOLD;
1263                         }
1264                         yp = winy + font->ascent;
1265                 }
1266
1267                 /* Lookup character index with default font. */
1268                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1269                 if (glyphidx) {
1270                         specs[numspecs].font = font->match;
1271                         specs[numspecs].glyph = glyphidx;
1272                         specs[numspecs].x = (short)xp;
1273                         specs[numspecs].y = (short)yp;
1274                         xp += runewidth;
1275                         numspecs++;
1276                         continue;
1277                 }
1278
1279                 /* Fallback on font cache, search the font cache for match. */
1280                 for (f = 0; f < frclen; f++) {
1281                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1282                         /* Everything correct. */
1283                         if (glyphidx && frc[f].flags == frcflags)
1284                                 break;
1285                         /* We got a default font for a not found glyph. */
1286                         if (!glyphidx && frc[f].flags == frcflags
1287                                         && frc[f].unicodep == rune) {
1288                                 break;
1289                         }
1290                 }
1291
1292                 /* Nothing was found. Use fontconfig to find matching font. */
1293                 if (f >= frclen) {
1294                         if (!font->set)
1295                                 font->set = FcFontSort(0, font->pattern,
1296                                                        1, 0, &fcres);
1297                         fcsets[0] = font->set;
1298
1299                         /*
1300                          * Nothing was found in the cache. Now use
1301                          * some dozen of Fontconfig calls to get the
1302                          * font for one single character.
1303                          *
1304                          * Xft and fontconfig are design failures.
1305                          */
1306                         fcpattern = FcPatternDuplicate(font->pattern);
1307                         fccharset = FcCharSetCreate();
1308
1309                         FcCharSetAddChar(fccharset, rune);
1310                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1311                                         fccharset);
1312                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1313
1314                         FcConfigSubstitute(0, fcpattern,
1315                                         FcMatchPattern);
1316                         FcDefaultSubstitute(fcpattern);
1317
1318                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1319                                         fcpattern, &fcres);
1320
1321                         /* Allocate memory for the new cache entry. */
1322                         if (frclen >= frccap) {
1323                                 frccap += 16;
1324                                 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1325                         }
1326
1327                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1328                                         fontpattern);
1329                         if (!frc[frclen].font)
1330                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1331                                         strerror(errno));
1332                         frc[frclen].flags = frcflags;
1333                         frc[frclen].unicodep = rune;
1334
1335                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1336
1337                         f = frclen;
1338                         frclen++;
1339
1340                         FcPatternDestroy(fcpattern);
1341                         FcCharSetDestroy(fccharset);
1342                 }
1343
1344                 specs[numspecs].font = frc[f].font;
1345                 specs[numspecs].glyph = glyphidx;
1346                 specs[numspecs].x = (short)xp;
1347                 specs[numspecs].y = (short)yp;
1348                 xp += runewidth;
1349                 numspecs++;
1350         }
1351
1352         return numspecs;
1353 }
1354
1355 void
1356 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1357 {
1358         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1359         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1360             width = charlen * win.cw;
1361         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1362         XRenderColor colfg, colbg;
1363         XRectangle r;
1364
1365         /* Fallback on color display for attributes not supported by the font */
1366         if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1367                 if (dc.ibfont.badslant || dc.ibfont.badweight)
1368                         base.fg = defaultattr;
1369         } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1370             (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1371                 base.fg = defaultattr;
1372         }
1373
1374         if (IS_TRUECOL(base.fg)) {
1375                 colfg.alpha = 0xffff;
1376                 colfg.red = TRUERED(base.fg);
1377                 colfg.green = TRUEGREEN(base.fg);
1378                 colfg.blue = TRUEBLUE(base.fg);
1379                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1380                 fg = &truefg;
1381         } else {
1382                 fg = &dc.col[base.fg];
1383         }
1384
1385         if (IS_TRUECOL(base.bg)) {
1386                 colbg.alpha = 0xffff;
1387                 colbg.green = TRUEGREEN(base.bg);
1388                 colbg.red = TRUERED(base.bg);
1389                 colbg.blue = TRUEBLUE(base.bg);
1390                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1391                 bg = &truebg;
1392         } else {
1393                 bg = &dc.col[base.bg];
1394         }
1395
1396         /* Change basic system colors [0-7] to bright system colors [8-15] */
1397         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1398                 fg = &dc.col[base.fg + 8];
1399
1400         if (IS_SET(MODE_REVERSE)) {
1401                 if (fg == &dc.col[defaultfg]) {
1402                         fg = &dc.col[defaultbg];
1403                 } else {
1404                         colfg.red = ~fg->color.red;
1405                         colfg.green = ~fg->color.green;
1406                         colfg.blue = ~fg->color.blue;
1407                         colfg.alpha = fg->color.alpha;
1408                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1409                                         &revfg);
1410                         fg = &revfg;
1411                 }
1412
1413                 if (bg == &dc.col[defaultbg]) {
1414                         bg = &dc.col[defaultfg];
1415                 } else {
1416                         colbg.red = ~bg->color.red;
1417                         colbg.green = ~bg->color.green;
1418                         colbg.blue = ~bg->color.blue;
1419                         colbg.alpha = bg->color.alpha;
1420                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1421                                         &revbg);
1422                         bg = &revbg;
1423                 }
1424         }
1425
1426         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1427                 colfg.red = fg->color.red / 2;
1428                 colfg.green = fg->color.green / 2;
1429                 colfg.blue = fg->color.blue / 2;
1430                 colfg.alpha = fg->color.alpha;
1431                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1432                 fg = &revfg;
1433         }
1434
1435         if (base.mode & ATTR_REVERSE) {
1436                 temp = fg;
1437                 fg = bg;
1438                 bg = temp;
1439         }
1440
1441         if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1442                 fg = bg;
1443
1444         if (base.mode & ATTR_INVISIBLE)
1445                 fg = bg;
1446
1447         /* Intelligent cleaning up of the borders. */
1448         if (x == 0) {
1449                 xclear(0, (y == 0)? 0 : winy, borderpx,
1450                         winy + win.ch +
1451                         ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1452         }
1453         if (winx + width >= borderpx + win.tw) {
1454                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1455                         ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1456         }
1457         if (y == 0)
1458                 xclear(winx, 0, winx + width, borderpx);
1459         if (winy + win.ch >= borderpx + win.th)
1460                 xclear(winx, winy + win.ch, winx + width, win.h);
1461
1462         /* Clean up the region we want to draw to. */
1463         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1464
1465         /* Set the clip region because Xft is sometimes dirty. */
1466         r.x = 0;
1467         r.y = 0;
1468         r.height = win.ch;
1469         r.width = width;
1470         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1471
1472         /* Render the glyphs. */
1473         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1474
1475         /* Render underline and strikethrough. */
1476         if (base.mode & ATTR_UNDERLINE) {
1477                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1478                                 width, 1);
1479         }
1480
1481         if (base.mode & ATTR_STRUCK) {
1482                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1483                                 width, 1);
1484         }
1485
1486         /* Reset clip to none. */
1487         XftDrawSetClip(xw.draw, 0);
1488 }
1489
1490 void
1491 xdrawglyph(Glyph g, int x, int y)
1492 {
1493         int numspecs;
1494         XftGlyphFontSpec spec;
1495
1496         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1497         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1498 }
1499
1500 void
1501 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1502 {
1503         Color drawcol;
1504
1505         /* remove the old cursor */
1506         if (selected(ox, oy))
1507                 og.mode ^= ATTR_REVERSE;
1508         xdrawglyph(og, ox, oy);
1509
1510         if (IS_SET(MODE_HIDE))
1511                 return;
1512
1513         /*
1514          * Select the right color for the right mode.
1515          */
1516         g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1517
1518         if (IS_SET(MODE_REVERSE)) {
1519                 g.mode |= ATTR_REVERSE;
1520                 g.bg = defaultfg;
1521                 if (selected(cx, cy)) {
1522                         drawcol = dc.col[defaultcs];
1523                         g.fg = defaultrcs;
1524                 } else {
1525                         drawcol = dc.col[defaultrcs];
1526                         g.fg = defaultcs;
1527                 }
1528         } else {
1529                 if (selected(cx, cy)) {
1530                         g.fg = defaultfg;
1531                         g.bg = defaultrcs;
1532                 } else {
1533                         g.fg = defaultbg;
1534                         g.bg = defaultcs;
1535                 }
1536                 drawcol = dc.col[g.bg];
1537         }
1538
1539         /* draw the new one */
1540         if (IS_SET(MODE_FOCUSED)) {
1541                 switch (win.cursor) {
1542                 case 0: /* Blinking block */
1543                 case 1: /* Blinking block (default) */
1544                         if (IS_SET(MODE_BLINK))
1545                                 break;
1546                         /* FALLTHROUGH */
1547                 case 2: /* Steady block */
1548                         xdrawglyph(g, cx, cy);
1549                         break;
1550                 case 3: /* Blinking underline */
1551                         if (IS_SET(MODE_BLINK))
1552                                 break;
1553                         /* FALLTHROUGH */
1554                 case 4: /* Steady underline */
1555                         XftDrawRect(xw.draw, &drawcol,
1556                                         borderpx + cx * win.cw,
1557                                         borderpx + (cy + 1) * win.ch - \
1558                                                 cursorthickness,
1559                                         win.cw, cursorthickness);
1560                         break;
1561                 case 5: /* Blinking bar */
1562                         if (IS_SET(MODE_BLINK))
1563                                 break;
1564                         /* FALLTHROUGH */
1565                 case 6: /* Steady bar */
1566                         XftDrawRect(xw.draw, &drawcol,
1567                                         borderpx + cx * win.cw,
1568                                         borderpx + cy * win.ch,
1569                                         cursorthickness, win.ch);
1570                         break;
1571                 case 7: /* Blinking st cursor */
1572                         if (IS_SET(MODE_BLINK))
1573                                 break;
1574                         /* FALLTHROUGH */
1575                 case 8: /* Steady st cursor */
1576                         g.u = stcursor;
1577                         xdrawglyph(g, cx, cy);
1578                         break;
1579                 }
1580         } else {
1581                 XftDrawRect(xw.draw, &drawcol,
1582                                 borderpx + cx * win.cw,
1583                                 borderpx + cy * win.ch,
1584                                 win.cw - 1, 1);
1585                 XftDrawRect(xw.draw, &drawcol,
1586                                 borderpx + cx * win.cw,
1587                                 borderpx + cy * win.ch,
1588                                 1, win.ch - 1);
1589                 XftDrawRect(xw.draw, &drawcol,
1590                                 borderpx + (cx + 1) * win.cw - 1,
1591                                 borderpx + cy * win.ch,
1592                                 1, win.ch - 1);
1593                 XftDrawRect(xw.draw, &drawcol,
1594                                 borderpx + cx * win.cw,
1595                                 borderpx + (cy + 1) * win.ch - 1,
1596                                 win.cw, 1);
1597         }
1598 }
1599
1600 void
1601 xsetenv(void)
1602 {
1603         char buf[sizeof(long) * 8 + 1];
1604
1605         snprintf(buf, sizeof(buf), "%lu", xw.win);
1606         setenv("WINDOWID", buf, 1);
1607 }
1608
1609 void
1610 xsettitle(char *p)
1611 {
1612         XTextProperty prop;
1613         DEFAULT(p, opt_title);
1614
1615         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1616                         &prop);
1617         XSetWMName(xw.dpy, xw.win, &prop);
1618         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1619         XFree(prop.value);
1620 }
1621
1622 int
1623 xstartdraw(void)
1624 {
1625         return IS_SET(MODE_VISIBLE);
1626 }
1627
1628 void
1629 xdrawline(Line line, int x1, int y1, int x2)
1630 {
1631         int i, x, ox, numspecs;
1632         Glyph base, new;
1633         XftGlyphFontSpec *specs = xw.specbuf;
1634
1635         numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1636         i = ox = 0;
1637         for (x = x1; x < x2 && i < numspecs; x++) {
1638                 new = line[x];
1639                 if (new.mode == ATTR_WDUMMY)
1640                         continue;
1641                 if (selected(x, y1))
1642                         new.mode ^= ATTR_REVERSE;
1643                 if (i > 0 && ATTRCMP(base, new)) {
1644                         xdrawglyphfontspecs(specs, base, i, ox, y1);
1645                         specs += i;
1646                         numspecs -= i;
1647                         i = 0;
1648                 }
1649                 if (i == 0) {
1650                         ox = x;
1651                         base = new;
1652                 }
1653                 i++;
1654         }
1655         if (i > 0)
1656                 xdrawglyphfontspecs(specs, base, i, ox, y1);
1657 }
1658
1659 void
1660 xfinishdraw(void)
1661 {
1662         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1663                         win.h, 0, 0);
1664         XSetForeground(xw.dpy, dc.gc,
1665                         dc.col[IS_SET(MODE_REVERSE)?
1666                                 defaultfg : defaultbg].pixel);
1667 }
1668
1669 void
1670 xximspot(int x, int y)
1671 {
1672         if (xw.ime.xic == NULL)
1673                 return;
1674
1675         xw.ime.spot.x = borderpx + x * win.cw;
1676         xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1677
1678         XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1679 }
1680
1681 void
1682 expose(XEvent *ev)
1683 {
1684         redraw();
1685 }
1686
1687 void
1688 visibility(XEvent *ev)
1689 {
1690         XVisibilityEvent *e = &ev->xvisibility;
1691
1692         MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1693 }
1694
1695 void
1696 unmap(XEvent *ev)
1697 {
1698         win.mode &= ~MODE_VISIBLE;
1699 }
1700
1701 void
1702 xsetpointermotion(int set)
1703 {
1704         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1705         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1706 }
1707
1708 void
1709 xsetmode(int set, unsigned int flags)
1710 {
1711         int mode = win.mode;
1712         MODBIT(win.mode, set, flags);
1713         if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1714                 redraw();
1715 }
1716
1717 int
1718 xsetcursor(int cursor)
1719 {
1720         if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1721                 return 1;
1722         win.cursor = cursor;
1723         cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1724                        win.cursor == 3 || win.cursor == 5 ||
1725                        win.cursor == 7;
1726         return 0;
1727 }
1728
1729 void
1730 xseturgency(int add)
1731 {
1732         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1733
1734         MODBIT(h->flags, add, XUrgencyHint);
1735         XSetWMHints(xw.dpy, xw.win, h);
1736         XFree(h);
1737 }
1738
1739 void
1740 xbell(void)
1741 {
1742         if (!(IS_SET(MODE_FOCUSED)))
1743                 xseturgency(1);
1744         if (bellvolume)
1745                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1746 }
1747
1748 void
1749 focus(XEvent *ev)
1750 {
1751         XFocusChangeEvent *e = &ev->xfocus;
1752
1753         if (e->mode == NotifyGrab)
1754                 return;
1755
1756         if (ev->type == FocusIn) {
1757                 if (xw.ime.xic)
1758                         XSetICFocus(xw.ime.xic);
1759                 win.mode |= MODE_FOCUSED;
1760                 xseturgency(0);
1761                 if (IS_SET(MODE_FOCUS))
1762                         ttywrite("\033[I", 3, 0);
1763         } else {
1764                 if (xw.ime.xic)
1765                         XUnsetICFocus(xw.ime.xic);
1766                 win.mode &= ~MODE_FOCUSED;
1767                 if (IS_SET(MODE_FOCUS))
1768                         ttywrite("\033[O", 3, 0);
1769         }
1770 }
1771
1772 int
1773 match(uint mask, uint state)
1774 {
1775         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1776 }
1777
1778 char*
1779 kmap(KeySym k, uint state)
1780 {
1781         Key *kp;
1782         int i;
1783
1784         /* Check for mapped keys out of X11 function keys. */
1785         for (i = 0; i < LEN(mappedkeys); i++) {
1786                 if (mappedkeys[i] == k)
1787                         break;
1788         }
1789         if (i == LEN(mappedkeys)) {
1790                 if ((k & 0xFFFF) < 0xFD00)
1791                         return NULL;
1792         }
1793
1794         for (kp = key; kp < key + LEN(key); kp++) {
1795                 if (kp->k != k)
1796                         continue;
1797
1798                 if (!match(kp->mask, state))
1799                         continue;
1800
1801                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1802                         continue;
1803                 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1804                         continue;
1805
1806                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1807                         continue;
1808
1809                 return kp->s;
1810         }
1811
1812         return NULL;
1813 }
1814
1815 void
1816 kpress(XEvent *ev)
1817 {
1818         XKeyEvent *e = &ev->xkey;
1819         KeySym ksym;
1820         char buf[64], *customkey;
1821         int len;
1822         Rune c;
1823         Status status;
1824         Shortcut *bp;
1825
1826         if (IS_SET(MODE_KBDLOCK))
1827                 return;
1828
1829         if (xw.ime.xic)
1830                 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1831         else
1832                 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1833         /* 1. shortcuts */
1834         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1835                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1836                         bp->func(&(bp->arg));
1837                         return;
1838                 }
1839         }
1840
1841         /* 2. custom keys from config.h */
1842         if ((customkey = kmap(ksym, e->state))) {
1843                 ttywrite(customkey, strlen(customkey), 1);
1844                 return;
1845         }
1846
1847         /* 3. composed string from input method */
1848         if (len == 0)
1849                 return;
1850         if (len == 1 && e->state & Mod1Mask) {
1851                 if (IS_SET(MODE_8BIT)) {
1852                         if (*buf < 0177) {
1853                                 c = *buf | 0x80;
1854                                 len = utf8encode(c, buf);
1855                         }
1856                 } else {
1857                         buf[1] = buf[0];
1858                         buf[0] = '\033';
1859                         len = 2;
1860                 }
1861         }
1862         ttywrite(buf, len, 1);
1863 }
1864
1865 void
1866 cmessage(XEvent *e)
1867 {
1868         /*
1869          * See xembed specs
1870          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1871          */
1872         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1873                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1874                         win.mode |= MODE_FOCUSED;
1875                         xseturgency(0);
1876                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1877                         win.mode &= ~MODE_FOCUSED;
1878                 }
1879         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1880                 ttyhangup();
1881                 exit(0);
1882         }
1883 }
1884
1885 void
1886 resize(XEvent *e)
1887 {
1888         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1889                 return;
1890
1891         cresize(e->xconfigure.width, e->xconfigure.height);
1892 }
1893
1894 void
1895 run(void)
1896 {
1897         XEvent ev;
1898         int w = win.w, h = win.h;
1899         fd_set rfd;
1900         int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1901         struct timespec seltv, *tv, now, lastblink, trigger;
1902         double timeout;
1903
1904         /* Waiting for window mapping */
1905         do {
1906                 XNextEvent(xw.dpy, &ev);
1907                 /*
1908                  * This XFilterEvent call is required because of XOpenIM. It
1909                  * does filter out the key event and some client message for
1910                  * the input method too.
1911                  */
1912                 if (XFilterEvent(&ev, None))
1913                         continue;
1914                 if (ev.type == ConfigureNotify) {
1915                         w = ev.xconfigure.width;
1916                         h = ev.xconfigure.height;
1917                 }
1918         } while (ev.type != MapNotify);
1919
1920         ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1921         cresize(w, h);
1922
1923         for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1924                 FD_ZERO(&rfd);
1925                 FD_SET(ttyfd, &rfd);
1926                 FD_SET(xfd, &rfd);
1927
1928                 if (XPending(xw.dpy))
1929                         timeout = 0;  /* existing events might not set xfd */
1930
1931                 seltv.tv_sec = timeout / 1E3;
1932                 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1933                 tv = timeout >= 0 ? &seltv : NULL;
1934
1935                 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1936                         if (errno == EINTR)
1937                                 continue;
1938                         die("select failed: %s\n", strerror(errno));
1939                 }
1940                 clock_gettime(CLOCK_MONOTONIC, &now);
1941
1942                 if (FD_ISSET(ttyfd, &rfd))
1943                         ttyread();
1944
1945                 xev = 0;
1946                 while (XPending(xw.dpy)) {
1947                         xev = 1;
1948                         XNextEvent(xw.dpy, &ev);
1949                         if (XFilterEvent(&ev, None))
1950                                 continue;
1951                         if (handler[ev.type])
1952                                 (handler[ev.type])(&ev);
1953                 }
1954
1955                 /*
1956                  * To reduce flicker and tearing, when new content or event
1957                  * triggers drawing, we first wait a bit to ensure we got
1958                  * everything, and if nothing new arrives - we draw.
1959                  * We start with trying to wait minlatency ms. If more content
1960                  * arrives sooner, we retry with shorter and shorter periods,
1961                  * and eventually draw even without idle after maxlatency ms.
1962                  * Typically this results in low latency while interacting,
1963                  * maximum latency intervals during `cat huge.txt`, and perfect
1964                  * sync with periodic updates from animations/key-repeats/etc.
1965                  */
1966                 if (FD_ISSET(ttyfd, &rfd) || xev) {
1967                         if (!drawing) {
1968                                 trigger = now;
1969                                 if (IS_SET(MODE_BLINK)) {
1970                                         win.mode ^= MODE_BLINK;
1971                                 }
1972                                 lastblink = now;
1973                                 drawing = 1;
1974                         }
1975                         timeout = (maxlatency - TIMEDIFF(now, trigger)) \
1976                                   / maxlatency * minlatency;
1977                         if (timeout > 0)
1978                                 continue;  /* we have time, try to find idle */
1979                 }
1980
1981                 /* idle detected or maxlatency exhausted -> draw */
1982                 timeout = -1;
1983                 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
1984                         timeout = blinktimeout - TIMEDIFF(now, lastblink);
1985                         if (timeout <= 0) {
1986                                 if (-timeout > blinktimeout) /* start visible */
1987                                         win.mode |= MODE_BLINK;
1988                                 win.mode ^= MODE_BLINK;
1989                                 tsetdirtattr(ATTR_BLINK);
1990                                 lastblink = now;
1991                                 timeout = blinktimeout;
1992                         }
1993                 }
1994
1995                 draw();
1996                 XFlush(xw.dpy);
1997                 drawing = 0;
1998         }
1999 }
2000
2001 int
2002 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2003 {
2004         char **sdst = dst;
2005         int *idst = dst;
2006         float *fdst = dst;
2007
2008         char fullname[256];
2009         char fullclass[256];
2010         char *type;
2011         XrmValue ret;
2012
2013         snprintf(fullname, sizeof(fullname), "%s.%s",
2014                         opt_name ? opt_name : "st", name);
2015         snprintf(fullclass, sizeof(fullclass), "%s.%s",
2016                         opt_class ? opt_class : "St", name);
2017         fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
2018
2019         XrmGetResource(db, fullname, fullclass, &type, &ret);
2020         if (ret.addr == NULL || strncmp("String", type, 64))
2021                 return 1;
2022
2023         switch (rtype) {
2024         case STRING:
2025                 *sdst = ret.addr;
2026                 break;
2027         case INTEGER:
2028                 *idst = strtoul(ret.addr, NULL, 10);
2029                 break;
2030         case FLOAT:
2031                 *fdst = strtof(ret.addr, NULL);
2032                 break;
2033         }
2034         return 0;
2035 }
2036
2037 void
2038 config_init(void)
2039 {
2040         char *resm;
2041         XrmDatabase db;
2042         ResourcePref *p;
2043
2044         XrmInitialize();
2045         resm = XResourceManagerString(xw.dpy);
2046         if (!resm)
2047                 return;
2048
2049         db = XrmGetStringDatabase(resm);
2050         for (p = resources; p < resources + LEN(resources); p++)
2051                 resource_load(db, p->name, p->type, p->dst);
2052 }
2053
2054 void
2055 usage(void)
2056 {
2057         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2058             " [-n name] [-o file]\n"
2059             "          [-T title] [-t title] [-w windowid]"
2060             " [[-e] command [args ...]]\n"
2061             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
2062             " [-n name] [-o file]\n"
2063             "          [-T title] [-t title] [-w windowid] -l line"
2064             " [stty_args ...]\n", argv0, argv0);
2065 }
2066
2067 int
2068 main(int argc, char *argv[])
2069 {
2070         xw.l = xw.t = 0;
2071         xw.isfixed = False;
2072         xsetcursor(cursorstyle);
2073
2074         ARGBEGIN {
2075         case 'a':
2076                 allowaltscreen = 0;
2077                 break;
2078         case 'c':
2079                 opt_class = EARGF(usage());
2080                 break;
2081         case 'e':
2082                 if (argc > 0)
2083                         --argc, ++argv;
2084                 goto run;
2085         case 'f':
2086                 opt_font = EARGF(usage());
2087                 break;
2088         case 'g':
2089                 xw.gm = XParseGeometry(EARGF(usage()),
2090                                 &xw.l, &xw.t, &cols, &rows);
2091                 break;
2092         case 'i':
2093                 xw.isfixed = 1;
2094                 break;
2095         case 'o':
2096                 opt_io = EARGF(usage());
2097                 break;
2098         case 'l':
2099                 opt_line = EARGF(usage());
2100                 break;
2101         case 'n':
2102                 opt_name = EARGF(usage());
2103                 break;
2104         case 't':
2105         case 'T':
2106                 opt_title = EARGF(usage());
2107                 break;
2108         case 'w':
2109                 opt_embed = EARGF(usage());
2110                 break;
2111         case 'v':
2112                 die("%s " VERSION "\n", argv0);
2113                 break;
2114         default:
2115                 usage();
2116         } ARGEND;
2117
2118 run:
2119         if (argc > 0) /* eat all remaining arguments */
2120                 opt_cmd = argv;
2121
2122         if (!opt_title)
2123                 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2124
2125         setlocale(LC_CTYPE, "");
2126         XSetLocaleModifiers("");
2127
2128         if(!(xw.dpy = XOpenDisplay(NULL)))
2129                 die("Can't open display\n");
2130
2131         config_init();
2132         cols = MAX(cols, 1);
2133         rows = MAX(rows, 1);
2134         tnew(cols, rows);
2135         xinit(cols, rows);
2136         xsetenv();
2137         selinit();
2138         run();
2139
2140         return 0;
2141 }